示例#1
0
        /// <summary>
        /// The generate response.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <IServerMessage> GenerateResponse(IServerMessage request)
        {
            var unitOfWork     = new UnitOfWork();
            var productList    = unitOfWork.ProductRepository.GetAllProducts();
            var productDtoList = new List <ProductDto>();

            foreach (var product in productList)
            {
                productDtoList.Add(new ProductDto()
                {
                    Id          = product.Id,
                    Weight      = product.Weight,
                    Sku         = product.Sku,
                    Name        = product.Name,
                    Description = product.Description,
                    Price       = product.Price,
                    State       = product.State,
                    Width       = product.Width,
                    Height      = product.Height,
                    Depth       = product.Depth
                });
            }
            // Console.WriteLine(ParserFactory.GetDataParser(request.DataType).SerializeData(productDtoList));
            return(new ServerMessage(request.Message + "Result", ParserFactory.GetDataParser(request.DataType).SerializeData(productDtoList)));
        }
示例#2
0
        public static MemoryStream WriteServerAction(this MemoryStream stream, IServerMessage message)
        {
            switch (message)
            {
            case AddedTileMessage msg:
                return(stream
                       .WriteInt((int)MessageToClient.AddedTile)
                       .WriteTile(msg.Tile));

            case RemovedTileMessage msg:
                return(stream
                       .WriteInt((int)MessageToClient.RemovedTile)
                       .WriteTileBaseData(msg.BaseData));

            case ClickedTileMessage msg:
                return(stream
                       .WriteInt((int)MessageToClient.ClickedTile)
                       .WriteTileBaseData(msg.BaseData));

            case GotRegionMessage msg:
                return(stream
                       .WriteInt((int)MessageToClient.GotRegion)
                       .WriteInt2(msg.SuperGridPosition)
                       .WriteList(msg.Tiles, WriteTile));

            case GotTrainsMessage msg:
                return(stream
                       .WriteInt((int)MessageToClient.GotTrains)
                       .WriteInt2(msg.SuperGridPosition)
                       .WriteList(msg.TrainTiles, WriteTile));

            default:
                throw new NotImplementedException();
            }
        }
示例#3
0
        /// <summary>
        /// The handle request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public async Task HandleRequest(IServerMessage request, IServerMessage response)
        {
            // Check if authentication passed
            if (request.User == null)
            {
                // Do nothing if this happens, the auth segement will have dealt
                // with this state
            }
            else if (!this._commands.ContainsKey(request.Message))
            {
                response.Message = $"{request.Message}Error";
                response.Body = ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                {
                    Reason = $"The operation {request.Message} is not available on the server",
                    Code = 100
                });
            }
            else
            {
                var commandResponse = await this._commands[request.Message].Execute(request);
                response.DataType = request.DataType;
                response.Body = commandResponse.Body;
                response.Message = commandResponse.Message;
                response.User = null;
            }

            // Check if there is a successor for this segment of the chain
            if (Successor != null)
            {
                await Successor.HandleRequest(request, response);
            }
        }
示例#4
0
        void OnSendRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            sendRequestQueue.Remove(req);

            // error reason if there is any. We will call the manager's Error function if it's not empty.
            string reason = string.Empty;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("Transport - " + this.Name, "Send - Request Finished Successfully! " + resp.DataAsText);

                    if (!string.IsNullOrEmpty(resp.DataAsText))
                    {
                        IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);

                        if (msg != null)
                        {
                            Connection.OnMessage(msg);
                        }
                    }
                }
                else
                {
                    reason = string.Format("Send - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Send - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // The request aborted, initiated by the user.
            case HTTPRequestStates.Aborted:
                reason = "Send - Request Aborted!";
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Send - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Send - Processing the request Timed Out!";
                break;
            }

            if (!string.IsNullOrEmpty(reason))
            {
                Connection.Error(reason);
            }
        }
示例#5
0
        public static IServerMessage Parse(IJsonEncoder encoder, string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
                return(null);
            }
            if (json.Length == 2 && json == "{}")
            {
                return(new KeepAliveMessage());
            }
            IDictionary <string, object> dictionary = null;

            try
            {
                dictionary = encoder.DecodeMessage(json);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
                return(null);

                IL_006f :;
            }
            if (dictionary == null)
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
                return(null);
            }
            IServerMessage serverMessage = null;

            serverMessage = (IServerMessage)(dictionary.ContainsKey("C") ? new MultiMessage() : (dictionary.ContainsKey("E") ? ((object)new FailureMessage()) : ((object)new ResultMessage())));
            serverMessage.Parse(dictionary);
            return(serverMessage);
        }
示例#6
0
 public void SendToAll(IServerMessage send)
 {
     foreach (var c in connectedUsers)
     {
         c.Server.Send(send);
     }
 }
示例#7
0
        /// <summary>
        /// The handle request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public async Task HandleRequest(IServerMessage request, IServerMessage response)
        {
            // Check if authentication passed
            if (request.User == null)
            {
                // Do nothing if this happens, the auth segement will have dealt
                // with this state
            }
            else if (!this._commands.ContainsKey(request.Message))
            {
                response.Message = $"{request.Message}Error";
                response.Body    = ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                {
                    Reason = $"The operation {request.Message} is not available on the server",
                    Code   = 100
                });
            }
            else
            {
                var commandResponse = await this._commands[request.Message].Execute(request);
                response.DataType = request.DataType;
                response.Body     = commandResponse.Body;
                response.Message  = commandResponse.Message;
                response.User     = null;
            }

            // Check if there is a successor for this segment of the chain
            if (Successor != null)
            {
                await Successor.HandleRequest(request, response);
            }
        }
示例#8
0
        /// <summary>
        /// When the json string is successfully parsed will return with an IServerMessage implementation.
        /// </summary>
        public static IServerMessage Parse(IJsonEncoder encoder, string json)
        {
            // Nothing to parse?
            if (string.IsNullOrEmpty(json))
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - called with empty or null string!");
                return(null);
            }

            // We don't have to do further decoding, if it's an empty json object, then it's a KeepAlive message from the server
            if (json.Length == 2 && json == "{}")
            {
                return(new KeepAliveMessage());
            }

            IDictionary <string, object> msg = null;

            try
            {
                // try to decode the json message with the encoder
                msg = encoder.DecodeMessage(json);
            }
            catch (Exception ex)
            {
                HTTPManager.Logger.Exception("MessageFactory", "Parse - encoder.DecodeMessage", ex);
                return(null);
            }

            if (msg == null)
            {
                HTTPManager.Logger.Error("MessageFactory", "Parse - Json Decode failed for json string: \"" + json + "\"");
                return(null);
            }

            // "C" is for message id
            IServerMessage result = null;

            if (!msg.ContainsKey("C"))
            {
                // If there are no ErrorMessage in the object, then it was a success
                if (!msg.ContainsKey("E"))
                {
                    result = new ResultMessage();
                }
                else
                {
                    result = new FailureMessage();
                }
            }
            else
            {
                result = new MultiMessage();
            }

            result.Parse(msg);

            return(result);
        }
示例#9
0
 public ServerMessageData(IServerMessage data)
 {
     Id          = data.Id == Guid.Empty ? Guid.NewGuid() : data.Id;
     Provider    = data.Provider;
     MessageType = data.MessageType;
     Content     = data.Content;
     Timestamp   = data.Timestamp == DateTime.MinValue ? DateTime.Now : data.Timestamp;
     IsDeleted   = data.IsDeleted;
 }
示例#10
0
 public ServerMessageViewModel(IServerMessage data) : this(data.Id)
 {
     _provider    = data.Provider;
     _messageType = data.MessageType;
     _content     = data.Content;
     _timestamp   = data.Timestamp;
     _isDeleted   = data.IsDeleted;
     data.MessageType.TryParse(out _messageTypeEnum);
 }
示例#11
0
 private void WSocket_OnMessage(BestHTTP.WebSocket.WebSocket webSocket, string message)
 {
     if (webSocket == this.wSocket)
     {
         IServerMessage msg = TransportBase.Parse(base.Connection.JsonEncoder, message);
         if (msg != null)
         {
             base.Connection.OnMessage(msg);
         }
     }
 }
示例#12
0
 private void WSocket_OnMessage(VRC.Core.BestHTTP.WebSocket.WebSocket webSocket, string message)
 {
     if (webSocket == wSocket)
     {
         IServerMessage serverMessage = TransportBase.Parse(base.Connection.JsonEncoder, message);
         if (serverMessage != null)
         {
             base.Connection.OnMessage(serverMessage);
         }
     }
 }
        /// <summary>
        /// The handle request.
        /// </summary>
        /// <param name="request">
        /// The requst.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>

        public async Task HandleRequest(IServerMessage request, IServerMessage response)
        {
            var userOrionKey = ParserFactory.GetDataParser(request.DataType).ParseData <Key>(request.User);

            if (userOrionKey == null)
            {
                // Do something here to stop processing and return some error to the server to
                // inform the client that auth has failed.
                request.User = null;
                await this.Successor.HandleRequest(request, response);
            }

            var orionContext = new Orion(new DeleteMeLogger())
            {
                Communicator =
                {
                    ApiAuthenticator = new OrgStandardAuthenticator()
                    {
                        PublicKey = this.Config.SystemPublicKey,
                        SecertKey = this.Config.SystemSecretKey
                    }
                }
            };

            // Set the authentication Information
            var user = await orionContext.CreateUserController().GetUserProfile(userOrionKey, "Zeus");

            if (user?.Result?.Meta == null || !user.Result.Meta.Any(x => x.Key.Equals("UserType")))
            {
                request.User = null;
            }
            else
            {
                // Parse the Orion user data into local user data
                var firstOrDefault = user.Result.Meta.FirstOrDefault(x => x.Key.Equals("UserType"));
                if (firstOrDefault != null)
                {
                    var parsedUser =
                        UserFactory.GetUser(
                            (UserType)
                            (Convert.ToInt32(firstOrDefault.Value)));
                    parsedUser.Email     = user.Result.Email;
                    parsedUser.Firstname = user.Result.Firstname;
                    parsedUser.Surname   = user.Result.Surname;
                    parsedUser.Phone     = user.Result.Phone;
                    request.User         = ParserFactory.GetDataParser(request.DataType).SerializeData(parsedUser);
                }
            }

            // Check the user type which should be contained in User Meta.
            await this.Successor.HandleRequest(request, response);
        }
示例#14
0
        private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            if (req.State == HTTPRequestStates.Aborted)
            {
                HTTPManager.Logger.Warning("Transport - " + base.Name, "Poll - Request Aborted!");
            }
            else
            {
                pollRequest = null;
                string text = string.Empty;
                switch (req.State)
                {
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess)
                    {
                        HTTPManager.Logger.Information("Transport - " + base.Name, "Poll - Request Finished Successfully! " + resp.DataAsText);
                        IServerMessage serverMessage = TransportBase.Parse(base.Connection.JsonEncoder, resp.DataAsText);
                        if (serverMessage != null)
                        {
                            base.Connection.OnMessage(serverMessage);
                            MultiMessage multiMessage = serverMessage as MultiMessage;
                            if (multiMessage != null && multiMessage.PollDelay.HasValue)
                            {
                                PollDelay = multiMessage.PollDelay.Value;
                            }
                            LastPoll = DateTime.UtcNow;
                        }
                    }
                    else
                    {
                        text = $"Poll - Request Finished Successfully, but the server sent an error. Status Code: {resp.StatusCode}-{resp.Message} Message: {resp.DataAsText}";
                    }
                    break;

                case HTTPRequestStates.Error:
                    text = "Poll - Request Finished with Error! " + ((req.Exception == null) ? "No Exception" : (req.Exception.Message + "\n" + req.Exception.StackTrace));
                    break;

                case HTTPRequestStates.ConnectionTimedOut:
                    text = "Poll - Connection Timed Out!";
                    break;

                case HTTPRequestStates.TimedOut:
                    text = "Poll - Processing the request Timed Out!";
                    break;
                }
                if (!string.IsNullOrEmpty(text))
                {
                    base.Connection.Error(text);
                }
            }
        }
        /// <summary>
        /// The handle request.
        /// </summary>
        /// <param name="request">
        /// The requst.
        /// </param>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        
        public async Task HandleRequest(IServerMessage request, IServerMessage response)
        {
            var userOrionKey = ParserFactory.GetDataParser(request.DataType).ParseData<Key>(request.User);
            if (userOrionKey == null)
            {
                // Do something here to stop processing and return some error to the server to 
                // inform the client that auth has failed.
                request.User = null;
                await this.Successor.HandleRequest(request, response);
            }

            var orionContext = new Orion(new DeleteMeLogger())
            {
                Communicator =
                {
                    ApiAuthenticator = new OrgStandardAuthenticator()
                    {
                        PublicKey = this.Config.SystemPublicKey,
                        SecertKey = this.Config.SystemSecretKey
                    }
                }
            };

            // Set the authentication Information
            var user = await orionContext.CreateUserController().GetUserProfile(userOrionKey, "Zeus");
            if (user?.Result?.Meta == null || !user.Result.Meta.Any(x => x.Key.Equals("UserType")))
            {
                request.User = null;
            }
            else
            {
                // Parse the Orion user data into local user data
                var firstOrDefault = user.Result.Meta.FirstOrDefault(x => x.Key.Equals("UserType"));
                if (firstOrDefault != null)
                {
                    var parsedUser =
                        UserFactory.GetUser(
                            (UserType)
                                (Convert.ToInt32(firstOrDefault.Value)));
                    parsedUser.Email = user.Result.Email;
                    parsedUser.Firstname = user.Result.Firstname;
                    parsedUser.Surname = user.Result.Surname;
                    parsedUser.Phone = user.Result.Phone;
                    request.User = ParserFactory.GetDataParser(request.DataType).SerializeData(parsedUser);
                }
            }

            // Check the user type which should be contained in User Meta.
            await this.Successor.HandleRequest(request, response);

        }
示例#16
0
        void WSocket_OnMessage(WebSocket.WebSocket webSocket, string message)
        {
            if (webSocket != wSocket)
            {
                return;
            }

            IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message);

            if (msg != null)
            {
                Connection.OnMessage(msg);
            }
        }
示例#17
0
        private void OnConnectRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            string str = string.Empty;

            switch (req.State)
            {
            case HTTPRequestStates.Finished:
            {
                if (!resp.IsSuccess)
                {
                    str = $"Connect - Request Finished Successfully, but the server sent an error. Status Code: {resp.StatusCode}-{resp.Message} Message: {resp.DataAsText}";
                    break;
                }
                HTTPManager.Logger.Information("Transport - " + base.Name, "Connect - Request Finished Successfully! " + resp.DataAsText);
                base.OnConnected();
                IServerMessage msg = TransportBase.Parse(base.Connection.JsonEncoder, resp.DataAsText);
                if (msg != null)
                {
                    base.Connection.OnMessage(msg);
                    MultiMessage message2 = msg as MultiMessage;
                    if ((message2 != null) && message2.PollDelay.HasValue)
                    {
                        this.PollDelay = message2.PollDelay.Value;
                    }
                }
                break;
            }

            case HTTPRequestStates.Error:
                str = "Connect - Request Finished with Error! " + ((req.Exception == null) ? "No Exception" : (req.Exception.Message + "\n" + req.Exception.StackTrace));
                break;

            case HTTPRequestStates.Aborted:
                str = "Connect - Request Aborted!";
                break;

            case HTTPRequestStates.ConnectionTimedOut:
                str = "Connect - Connection Timed Out!";
                break;

            case HTTPRequestStates.TimedOut:
                str = "Connect - Processing the request Timed Out!";
                break;
            }
            if (!string.IsNullOrEmpty(str))
            {
                base.Connection.Error(str);
            }
        }
示例#18
0
        private MyBuffer MessageToBuffer(IServerMessage message)
        {
            if (!(message.GetType().GetCustomAttribute(typeof(ServerMessageTypeAttribute)) is ServerMessageTypeAttribute messageTypeAttr))
            {
                throw new NotImplementedException($"Not found message type for{message.GetType().Name}");
            }

            var mesageType = messageTypeAttr.ServerMessageType;

            var buff = MyBuffer.Create()
                       .SetUint8((byte)mesageType)
                       .SetData(message);

            return(buff);
        }
 private void OnEventSourceMessage(EventSource eventSource, Message message)
 {
     if (message.Data.Equals("initialized"))
     {
         OnConnected();
     }
     else
     {
         IServerMessage serverMessage = TransportBase.Parse(base.Connection.JsonEncoder, message.Data);
         if (serverMessage != null)
         {
             base.Connection.OnMessage(serverMessage);
         }
     }
 }
示例#20
0
        private void OnEventSourceMessage(EventSource eventSource, BestHTTP.ServerSentEvents.Message message)
        {
            if (message.Data.Equals("initialized"))
            {
                base.OnConnected();

                return;
            }

            IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message.Data);

            if (msg != null)
            {
                Connection.OnMessage(msg);
            }
        }
        private void OnSendRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            sendRequestQueue.Remove(req);
            string text = string.Empty;

            switch (req.State)
            {
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("Transport - " + base.Name, "Send - Request Finished Successfully! " + resp.DataAsText);
                    if (!string.IsNullOrEmpty(resp.DataAsText))
                    {
                        IServerMessage serverMessage = TransportBase.Parse(base.Connection.JsonEncoder, resp.DataAsText);
                        if (serverMessage != null)
                        {
                            base.Connection.OnMessage(serverMessage);
                        }
                    }
                }
                else
                {
                    text = $"Send - Request Finished Successfully, but the server sent an error. Status Code: {resp.StatusCode}-{resp.Message} Message: {resp.DataAsText}";
                }
                break;

            case HTTPRequestStates.Error:
                text = "Send - Request Finished with Error! " + ((req.Exception == null) ? "No Exception" : (req.Exception.Message + "\n" + req.Exception.StackTrace));
                break;

            case HTTPRequestStates.Aborted:
                text = "Send - Request Aborted!";
                break;

            case HTTPRequestStates.ConnectionTimedOut:
                text = "Send - Connection Timed Out!";
                break;

            case HTTPRequestStates.TimedOut:
                text = "Send - Processing the request Timed Out!";
                break;
            }
            if (!string.IsNullOrEmpty(text))
            {
                base.Connection.Error(text);
            }
        }
        void WSocket_OnMessage(WebSocket.WebSocket webSocket, string message)
        {
            if (webSocket != wSocket)
            {
                return;
            }

#if UNITY_EDITOR
            VKDebug.Log(message, VKCommon.HEX_GREEN);
#endif

            IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, message);

            if (msg != null)
            {
                Connection.OnMessage(msg);
            }
        }
示例#23
0
        void IServerMessage.Parse(object data)
        {
            IDictionary <string, object> dictionary = data as IDictionary <string, object>;

            MessageId = dictionary["C"].ToString();
            if (dictionary.TryGetValue("S", out object value))
            {
                IsInitialization = ((int.Parse(value.ToString()) == 1) ? true : false);
            }
            else
            {
                IsInitialization = false;
            }
            if (dictionary.TryGetValue("G", out value))
            {
                GroupsToken = value.ToString();
            }
            if (dictionary.TryGetValue("T", out value))
            {
                ShouldReconnect = ((int.Parse(value.ToString()) == 1) ? true : false);
            }
            else
            {
                ShouldReconnect = false;
            }
            if (dictionary.TryGetValue("L", out value))
            {
                PollDelay = TimeSpan.FromMilliseconds(double.Parse(value.ToString()));
            }
            IEnumerable enumerable = dictionary["M"] as IEnumerable;

            if (enumerable != null)
            {
                Data = new List <IServerMessage>();
                foreach (object item in enumerable)
                {
                    IDictionary <string, object> dictionary2 = item as IDictionary <string, object>;
                    IServerMessage serverMessage             = null;
                    serverMessage = ((dictionary2 == null) ? new DataMessage() : ((!dictionary2.ContainsKey("H")) ? ((!dictionary2.ContainsKey("I")) ? ((IServerMessage) new DataMessage()) : ((IServerMessage) new ProgressMessage())) : new MethodCallMessage()));
                    serverMessage.Parse(item);
                    Data.Add(serverMessage);
                }
            }
        }
示例#24
0
        /// <summary>
        /// The generate response.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="config">
        /// The config.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <IServerMessage> GenerateResponse(IServerMessage request)
        {
            var unitOfWork = new UnitOfWork();
            var productDto = ParserFactory.GetDataParser(request.DataType).ParseData <ProductDto>(request.Body);

            if (productDto == null)
            {
                return(new ServerMessage(request.Message + "Error",
                                         ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                {
                    Code = 101,
                    Reason = "Invalid DTO was provided"
                })));
            }

            var product = unitOfWork.ProductRepository.GetOrDefault(productDto.Id);

            if (product == null)
            {
                return(new ServerMessage(request.Message + "Error",
                                         ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                {
                    Code = 102,
                    Reason = "Invalid ID provided for an entity in the database"
                })));
            }

            return(new ServerMessage(request.Message + "Result",
                                     ParserFactory.GetDataParser(request.DataType).SerializeData(new ProductDto()
            {
                Id = product.Id,
                Weight = product.Weight,
                Sku = product.Sku,
                Name = product.Name,
                Description = product.Description,
                Price = product.Price,
                State = product.State,
                Width = product.Width,
                Height = product.Height,
                Depth = product.Depth
            })));
        }
示例#25
0
        /// <summary>
        /// The generate response.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="config">
        /// The config.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task<IServerMessage> GenerateResponse(IServerMessage request)
        {
            var unitOfWork = new UnitOfWork();
            var productDto = ParserFactory.GetDataParser(request.DataType).ParseData<ProductDto>(request.Body);
            if (productDto == null)
            {
                return new ServerMessage(request.Message + "Error",
                    ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                    {
                        Code = 101,
                        Reason = "Invalid DTO was provided"
                    }));
            }

            var product = unitOfWork.ProductRepository.GetOrDefault(productDto.Id);
            if (product == null)
            {
                return new ServerMessage(request.Message + "Error",
                    ParserFactory.GetDataParser(request.DataType).SerializeData(new ErrorResponse()
                    {
                        Code = 102,
                        Reason = "Invalid ID provided for an entity in the database"
                    }));
            }

            return new ServerMessage(request.Message + "Result",
                ParserFactory.GetDataParser(request.DataType).SerializeData(new ProductDto()
                {
                    Id = product.Id,
                    Weight = product.Weight,
                    Sku = product.Sku,
                    Name = product.Name,
                    Description = product.Description,
                    Price = product.Price,
                    State = product.State,
                    Width = product.Width,
                    Height = product.Height,
                    Depth = product.Depth
                }));

        }
示例#26
0
        /// <summary>
        /// Trigger event handlers for an incoming message
        /// </summary>
        /// <param name="message">Incoming message from IRC server</param>
        /// <remarks>Automatically determines types using reflection</remarks>
        public void Trigger(IServerMessage message)
        {
            if (message == null)
            {
                return;
            }

            var messageType = message.GetType();

            var getHandlerMethod = typeof(EventHub).GetMethod(nameof(GetHandler), BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(messageType);
            var handler          = getHandlerMethod.Invoke(this, null);

            var genericArgsType = typeof(IrcMessageEventArgs <>).MakeGenericType(messageType);
            var args            = Activator.CreateInstance(genericArgsType, message);

            var handlerType = typeof(ServerMessageEventHandler <>).MakeGenericType(messageType);

            var receivedEvent = handlerType.GetMethod("OnReceived", BindingFlags.NonPublic | BindingFlags.Instance);

            receivedEvent.Invoke(handler, new object[] { args });
        }
示例#27
0
        /// <summary>
        /// The send server message.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// The <see cref="IServerMessage"/>.
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public IServerMessage SendServerMessage(IServerMessage message)
        {
            using (var serverConnection = new TcpClient())
            {
                serverConnection.Connect(this.Endpoint, this.Port);
                if (!serverConnection.Connected)
                {
                    throw new Exception($"Failed to connect to Zeus server at endpoint {this.Endpoint} on port {this.Port}");
                }

                var stream = serverConnection.GetStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, (ServerMessage)message);
                try
                {
                    return (ServerMessage)formatter.Deserialize(stream);
                }
                catch (Exception)
                {
                    throw new Exception("Invalid response from server");
                }
            }
        }
示例#28
0
        /// <summary>
        /// The send server message.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// The <see cref="IServerMessage"/>.
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public IServerMessage SendServerMessage(IServerMessage message)
        {
            using (var serverConnection = new TcpClient())
            {
                serverConnection.Connect(this.Endpoint, this.Port);
                if (!serverConnection.Connected)
                {
                    throw new Exception($"Failed to connect to Zeus server at endpoint {this.Endpoint} on port {this.Port}");
                }

                var stream    = serverConnection.GetStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, (ServerMessage)message);
                try
                {
                    return((ServerMessage)formatter.Deserialize(stream));
                }
                catch (Exception)
                {
                    throw new Exception("Invalid response from server");
                }
            }
        }
示例#29
0
 /// <summary>
 /// The generate response.
 /// </summary>
 /// <param name="request">
 /// The request.
 /// </param>
 /// <returns>
 /// The <see cref="Task"/>.
 /// </returns>
 public async Task<IServerMessage> GenerateResponse(IServerMessage request)
 {
     var unitOfWork = new UnitOfWork();
     var productList = unitOfWork.ProductRepository.GetAllProducts();
     var productDtoList = new List<ProductDto>();
     foreach (var product in productList)
     {
         productDtoList.Add(new ProductDto()
         {
             Id = product.Id,
             Weight = product.Weight,
             Sku = product.Sku,
             Name = product.Name,
             Description = product.Description,
             Price = product.Price,
             State = product.State,
             Width = product.Width,
             Height = product.Height,
             Depth = product.Depth
         });
     }
     // Console.WriteLine(ParserFactory.GetDataParser(request.DataType).SerializeData(productDtoList));
     return new ServerMessage(request.Message + "Result", ParserFactory.GetDataParser(request.DataType).SerializeData(productDtoList));
 }
示例#30
0
 /// <summary>
 /// The execute.
 /// </summary>
 /// <param name="request">
 /// The request.
 /// </param>
 /// <returns>
 /// The <see cref="Task"/>.
 /// </returns>
 public Task<IServerMessage> Execute(IServerMessage request)
 {
     return new ProcessOrder().GenerateResponse(request);
 }
 public ServerMessageCommand(IServerMessage message)
 {
     _message = message;
 }
示例#32
0
 /// <summary>
 /// The execute.
 /// </summary>
 /// <param name="request">
 /// The request.
 /// </param>
 /// <returns>
 /// The <see cref="Task"/>.
 /// </returns>
 public Task<IServerMessage> Execute(IServerMessage request)
 {
     return new GetAllProducts().GenerateResponse(request);
 }
示例#33
0
文件: Hub.cs 项目: ubberkid/PeerATT
        /// <summary>
        /// Called when the client receives back messages as a result of a server method call.
        /// </summary>
        void IHub.OnMessage(IServerMessage msg)
        {
            ClientMessage originalMsg;

            UInt64 id = (msg as IHubMessage).InvocationId;
            if (!SentMessages.TryGetValue(id, out originalMsg))
            {
                // This can happen when a result message removes the ClientMessage from the SentMessages dictionary,
                //  then a late come progress message tries to access it
                HTTPManager.Logger.Warning("Hub - " + this.Name, "OnMessage - Sent message not found with id: " + id.ToString());
                return;
            }

            switch(msg.Type)
            {
                case MessageTypes.Result:
                    ResultMessage result = msg as ResultMessage;

                    // Merge the incoming State before firing the events
                    MergeState(result.State);

                    if (originalMsg.ResultCallback != null)
                    {
                        try
                        {
                            originalMsg.ResultCallback(this, originalMsg, result);
                        }
                        catch(Exception ex)
                        {
                            HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultCallback", ex);
                        }
                    }

                    SentMessages.Remove(id);

                    break;

                case MessageTypes.Failure:
                    FailureMessage error = msg as FailureMessage;

                    // Merge the incoming State before firing the events
                    MergeState(error.State);

                    if (originalMsg.ResultErrorCallback != null)
                    {
                        try
                        {
                            originalMsg.ResultErrorCallback(this, originalMsg, error);
                        }
                        catch(Exception ex)
                        {
                            HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultErrorCallback", ex);
                        }
                    }

                    SentMessages.Remove(id);
                    break;

                case MessageTypes.Progress:
                    if (originalMsg.ProgressCallback != null)
                    {
                        try
                        {
                            originalMsg.ProgressCallback(this, originalMsg, msg as ProgressMessage);
                        }
                        catch(Exception ex)
                        {
                            HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ProgressCallback", ex);
                        }
                    }
                    break;
            }
        }
示例#34
0
        public async Task<IServerMessage> GenerateResponse(IServerMessage request)
        {
            var orderDto = ParserFactory.GetDataParser(request.DataType).ParseData<OrderDto>(request.Body);

            var products = new List<Product>();
            var stopWatch = new Stopwatch();
            stopWatch.Start();
            Parallel.ForEach(orderDto.Products.Select(x => x.Id).ToList(), (currentProductId) =>
            {
                var unitOfWork = new UnitOfWork();
                var product = unitOfWork.ProductRepository.GetOrDefault(currentProductId);
                if (product == null)
                {
                    return;
                }
                lock (products)
                {
                    products.Add(product);
                }
            });
            stopWatch.Stop();
            Console.WriteLine(stopWatch.Elapsed);

            if (products.Count < orderDto.Products.Count)
            {
                return ErrorFactory.GetError(request.Message, 103, request.DataType);
            }

            var itemsForfulfilment = new List<IItem>();
            foreach (var product in products)
            {
                var bestItemPriority = -1;
                var availableItems = new UnitOfWork().ItemRepository.GetAvailableItemByProduct(product);
                var bestItem = availableItems.FirstOrDefault();
                var itemLock = new object();
                if (bestItem == null)
                {
                    return ErrorFactory.GetError(request.Message, 104, request.DataType);
                }

                Parallel.ForEach(availableItems.Where(i => itemsForfulfilment.All(x => x.Id != i.Id)), (item) =>
                {
                    // This is executed in parallel because it may become the case in the future
                    // that the algortihm that calculates the priority for a specifc product
                    // is computationally expensive and as such this is a good candidate for 
                    // threading, although concurrently the gains are minimal if any!
                    // It will also improve performance as the stock of a product grows
                    // -- Strategy --
                    var itemPriority = product.Priority.CalculatePriority(item, product);
                    lock (itemLock)
                    {
                        if (itemPriority > bestItemPriority)
                        {
                            bestItem = item;
                            bestItemPriority = itemPriority;
                        }
                    }
                });
                itemsForfulfilment.Add(bestItem);
            }

            // Now we need to make changes to the add them to the relevant sector and
            // update the state. Unit of work encapsulates all below operations
            var updateItems = new UnitOfWork();
            foreach (var item in itemsForfulfilment)
            {
                item.State = ItemState.AwaitingPicker;
                item.QueuedTime = DateTime.Now;
                updateItems.ItemRepository.Update(item);
            }

            // Create the order and commit it to persistance
            var order = new Order()
            {
                Items = itemsForfulfilment,
                Status = OrderStatus.Recieved,
                ShippingAddress = orderDto.ShippingAddress
            };
            updateItems.OrderRepository.Add(order);
            await updateItems.SaveChangesAsync();

            // End of unit of work, changes have been saved
            // ------
            // Lets inform the user that there order has been processed. We are going to use the 
            // bridge in this case
            var customer = ParserFactory.GetDataParser(request.DataType).ParseData<Customer>(request.User);
            var communication = new UserCommunication()
            {
                Subject = "Order Update ",
                Endpoint = customer.Phone,
                Body = $" Hey {customer.Firstname}, your order has been placed successfully. Thanks for using Zeus Solutions." +
                       $" Your order will be shipped to {orderDto.ShippingAddress}"
            };

            // Use SMS to send order info - BRIDGE
            communication.CommunicationCommunicator = new SmsSender();
            communication.Send();
            return new ServerMessage(request.Message + "Result", ParserFactory.GetDataParser(request.DataType).SerializeData(new OrderResultDto() { Success = true }));
        }
        void IServerMessage.Parse(object data)
        {
            IDictionary <string, object> dic = data as IDictionary <string, object>;
            object value;

            this.MessageId = dic["C"].ToString();

            if (dic.TryGetValue("S", out value))
            {
                IsInitialization = int.Parse(value.ToString()) == 1 ? true : false;
            }
            else
            {
                IsInitialization = false;
            }

            if (dic.TryGetValue("G", out value))
            {
                GroupsToken = value.ToString();
            }

            if (dic.TryGetValue("T", out value))
            {
                ShouldReconnect = int.Parse(value.ToString()) == 1 ? true : false;
            }
            else
            {
                ShouldReconnect = false;
            }

            if (dic.TryGetValue("L", out value))
            {
                PollDelay = TimeSpan.FromMilliseconds(double.Parse(value.ToString()));
            }

            IEnumerable enumerable = dic["M"] as IEnumerable;

            if (enumerable != null)
            {
                Data = new List <IServerMessage>();

                foreach (object subData in enumerable)
                {
                    IDictionary <string, object> subObj = subData as IDictionary <string, object>;

                    IServerMessage subMsg = null;

                    if (subObj != null)
                    {
                        if (subObj.ContainsKey("H"))
                        {
                            subMsg = new MethodCallMessage();
                        }
                        else if (subObj.ContainsKey("I"))
                        {
                            subMsg = new ProgressMessage();
                        }
                        else
                        {
                            subMsg = new DataMessage();
                        }
                    }
                    else
                    {
                        subMsg = new DataMessage();
                    }

                    subMsg.Parse(subData);

                    Data.Add(subMsg);
                }
            }
        }
示例#36
0
 private void SendAsync(IServerMessage message)
 {
     // Dirty typecast (OH NOEZ AGAIN)
     _client.GetStream().Write(message.SerializedMessage, 0, 8 + (int)message.OptionsSize + (int)message.ContentSize);
     _client.GetStream().Flush();
 }
示例#37
0
        /// <summary>
        /// Called when we receive a message from the server
        /// </summary>
        void IConnection.OnMessage(IServerMessage msg)
        {
            if (this.State == ConnectionStates.Closed)
            {
                return;
            }

            // Store messages that we receive while we are connecting
            if (this.State == ConnectionStates.Connecting)
            {
                if (BufferedMessages == null)
                {
                    BufferedMessages = new List <IServerMessage>();
                }

                BufferedMessages.Add(msg);

                return;
            }

            LastMessageReceivedAt = DateTime.UtcNow;

            switch (msg.Type)
            {
            case MessageTypes.Multiple:
                LastReceivedMessage = msg as MultiMessage;

                // Not received in the reconnect process, so we can't rely on it
                if (LastReceivedMessage.IsInitialization)
                {
                    HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Init");
                }

                if (LastReceivedMessage.GroupsToken != null)
                {
                    GroupsToken = LastReceivedMessage.GroupsToken;
                }

                if (LastReceivedMessage.ShouldReconnect)
                {
                    HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Should Reconnect");

                    Reconnect();

                    // Should we return here not processing the messages that may come with it?
                    //return;
                }

                if (LastReceivedMessage.Data != null)
                {
                    for (int i = 0; i < LastReceivedMessage.Data.Count; ++i)
                    {
                        (this as IConnection).OnMessage(LastReceivedMessage.Data[i]);
                    }
                }

                break;

            case MessageTypes.MethodCall:
                MethodCallMessage methodCall = msg as MethodCallMessage;

                Hub hub = this[methodCall.Hub];

                if (hub != null)
                {
                    (hub as IHub).OnMethod(methodCall);
                }
                else
                {
                    HTTPManager.Logger.Warning("SignalR Connection", string.Format("Hub \"{0}\" not found!", methodCall.Hub));
                }

                break;

            case MessageTypes.Result:
            case MessageTypes.Failure:
            case MessageTypes.Progress:
                UInt64 id = (msg as IHubMessage).InvocationId;
                hub = FindHub(id);
                if (hub != null)
                {
                    (hub as IHub).OnMessage(msg);
                }
                else
                {
                    HTTPManager.Logger.Warning("SignalR Connection", string.Format("No Hub found for Progress message! Id: {0}", id.ToString()));
                }
                break;

            case MessageTypes.Data:
                if (OnNonHubMessage != null)
                {
                    OnNonHubMessage(this, (msg as DataMessage).Data);
                }
                break;

            case MessageTypes.KeepAlive:
                break;

            default:
                HTTPManager.Logger.Warning("SignalR Connection", "Unknown message type received: " + msg.Type.ToString());
                break;
            }
        }
示例#38
0
        /// <summary>
        /// Called when we receive a message from the server
        /// </summary>
        void IConnection.OnMessage(IServerMessage msg)
        {
            if (this.State == ConnectionStates.Closed)
                return;

            // Store messages that we receive while we are connecting
            if (this.State == ConnectionStates.Connecting)
            {
                if (BufferedMessages == null)
                    BufferedMessages = new List<IServerMessage>();

                BufferedMessages.Add(msg);

                return;
            }

            LastMessageReceivedAt = DateTime.UtcNow;

            switch(msg.Type)
            {
                case MessageTypes.Multiple:
                    LastReceivedMessage = msg as MultiMessage;

                    // Not received in the reconnect process, so we can't rely on it
                    if (LastReceivedMessage.IsInitialization)
                        HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Init");

                    if (LastReceivedMessage.GroupsToken != null)
                        GroupsToken = LastReceivedMessage.GroupsToken;

                    if (LastReceivedMessage.ShouldReconnect)
                    {
                        HTTPManager.Logger.Information("SignalR Connection", "OnMessage - Should Reconnect");

                        Reconnect();

                        // Should we return here not processing the messages that may come with it?
                        //return;
                    }

                    if (LastReceivedMessage.Data != null)
                        for (int i = 0; i < LastReceivedMessage.Data.Count; ++i)
                            (this as IConnection).OnMessage(LastReceivedMessage.Data[i]);

                    break;

                case MessageTypes.MethodCall:
                    MethodCallMessage methodCall = msg as MethodCallMessage;

                    Hub hub = this[methodCall.Hub];

                    if (hub != null)
                        (hub as IHub).OnMethod(methodCall);
                    else
                        HTTPManager.Logger.Warning("SignalR Connection", string.Format("Hub \"{0}\" not found!", methodCall.Hub));

                    break;

                case MessageTypes.Result:
                case MessageTypes.Failure:
                case MessageTypes.Progress:
                    UInt64 id = (msg as IHubMessage).InvocationId;
                    hub = FindHub(id);
                    if (hub != null)
                        (hub as IHub).OnMessage(msg);
                    else
                        HTTPManager.Logger.Warning("SignalR Connection", string.Format("No Hub found for Progress message! Id: {0}", id.ToString()));
                    break;

                case MessageTypes.Data:
                    if (OnNonHubMessage != null)
                        OnNonHubMessage(this, (msg as DataMessage).Data);
                    break;

                case MessageTypes.KeepAlive:
                    break;

                default:
                    HTTPManager.Logger.Warning("SignalR Connection", "Unknown message type received: " + msg.Type.ToString());
                    break;
            }
        }
示例#39
0
 /// <summary>
 /// The execute.
 /// </summary>
 /// <param name="request">
 /// The request.
 /// </param>
 /// <returns>
 /// The <see cref="Task"/>.
 /// </returns>
 public Task <IServerMessage> Execute(IServerMessage request)
 {
     return(new GetAllProducts().GenerateResponse(request));
 }
 public BasicGameClientTCP(IServerMessage processor, ITCPInfo connectInfo)
 {
     _processor   = processor;
     _connectInfo = connectInfo;
 }
示例#41
0
        void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp)
        {
            // When Stop() called on the transport.
            // In Stop() we set the pollRequest to null, but a new poll request can be made after a quick reconnection, and there is a chanse that
            // in this handler function we can null out the new request. So we return early here.
            if (req.State == HTTPRequestStates.Aborted)
            {
                HTTPManager.Logger.Warning("Transport - " + this.Name, "Poll - Request Aborted!");
                return;
            }

            // Set the pollRequest to null, now we can send out a new one
            pollRequest = null;

            // error reason if there is any. We will call the manager's Error function if it's not empty.
            string reason = string.Empty;

            switch (req.State)
            {
            // The request finished without any problem.
            case HTTPRequestStates.Finished:
                if (resp.IsSuccess)
                {
                    HTTPManager.Logger.Information("Transport - " + this.Name, "Poll - Request Finished Successfully! " + resp.DataAsText);

                    IServerMessage msg = TransportBase.Parse(Connection.JsonEncoder, resp.DataAsText);

                    if (msg != null)
                    {
                        Connection.OnMessage(msg);

                        MultiMessage multiple = msg as MultiMessage;
                        if (multiple != null && multiple.PollDelay.HasValue)
                        {
                            PollDelay = multiple.PollDelay.Value;
                        }

                        LastPoll = DateTime.UtcNow;
                    }
                }
                else
                {
                    reason = string.Format("Poll - Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
                                           resp.StatusCode,
                                           resp.Message,
                                           resp.DataAsText);
                }
                break;

            // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
            case HTTPRequestStates.Error:
                reason = "Poll - Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception");
                break;

            // Ceonnecting to the server is timed out.
            case HTTPRequestStates.ConnectionTimedOut:
                reason = "Poll - Connection Timed Out!";
                break;

            // The request didn't finished in the given time.
            case HTTPRequestStates.TimedOut:
                reason = "Poll - Processing the request Timed Out!";
                break;
            }

            if (!string.IsNullOrEmpty(reason))
            {
                Connection.Error(reason);
            }
        }
示例#42
0
        /// <summary>
        /// Called when the client receives back messages as a result of a server method call.
        /// </summary>
        void IHub.OnMessage(IServerMessage msg)
        {
            ClientMessage originalMsg;

            UInt64 id = (msg as IHubMessage).InvocationId;

            if (!SentMessages.TryGetValue(id, out originalMsg))
            {
                // This can happen when a result message removes the ClientMessage from the SentMessages dictionary,
                //  then a late come progress message tries to access it
                HTTPManager.Logger.Warning("Hub - " + this.Name, "OnMessage - Sent message not found with id: " + id.ToString());
                return;
            }

            switch (msg.Type)
            {
            case MessageTypes.Result:
                ResultMessage result = msg as ResultMessage;

                // Merge the incoming State before firing the events
                MergeState(result.State);

                if (originalMsg.ResultCallback != null)
                {
                    try
                    {
                        originalMsg.ResultCallback(this, originalMsg, result);
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultCallback", ex);
                    }
                }

                SentMessages.Remove(id);

                break;

            case MessageTypes.Failure:
                FailureMessage error = msg as FailureMessage;

                // Merge the incoming State before firing the events
                MergeState(error.State);

                if (originalMsg.ResultErrorCallback != null)
                {
                    try
                    {
                        originalMsg.ResultErrorCallback(this, originalMsg, error);
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ResultErrorCallback", ex);
                    }
                }

                SentMessages.Remove(id);
                break;

            case MessageTypes.Progress:
                if (originalMsg.ProgressCallback != null)
                {
                    try
                    {
                        originalMsg.ProgressCallback(this, originalMsg, msg as ProgressMessage);
                    }
                    catch (Exception ex)
                    {
                        HTTPManager.Logger.Exception("Hub " + this.Name, "IHub.OnMessage - ProgressCallback", ex);
                    }
                }
                break;
            }
        }
示例#43
0
 public bool SendMessage(IServerMessage message)
 {
     if (_connectionActive && _client.Connected && message.SerializedMessage != null)
     {
         try
         {
             var sendingThread = new Thread(() => SendAsync(message));
             sendingThread.Start();
         }
         catch (Exception ex)
         {
             DiContainer.Container.Resolve<ILoggingManager>().LogError("An error occurred while trying to send a message to the server.", ex);
             return false;
         }
         return true;
     }
     return false;
 }