Esempio n. 1
0
        public async Task <IProduct> CreateProduct(string name, double price, ProductType productType)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddProduct, new ProductDTO {
                Name        = name,
                Price       = price,
                ProductType = productType
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add product! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is ProductDTO productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }

            return(productData.ToIProduct());
        }
Esempio n. 2
0
        public async Task <IOrder> CreateOrder(string clientUsername, DateTime orderDate, Dictionary <uint, uint> productIdQuantityMap, DateTime?deliveryDate)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddOrder, new OrderDTO {
                ClientUsername       = clientUsername,
                OrderDate            = orderDate,
                ProductIdQuantityMap = productIdQuantityMap,
                DeliveryDate         = deliveryDate
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add order! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is OrderDTO orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }

            return(orderData.ToIOrder());
        }
Esempio n. 3
0
        public async Task <IClient> CreateClient(string username, string firstName, string lastName, string street, uint streetNumber,
                                                 string phoneNumber)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.AddClient, new ClientDTO {
                Username     = username,
                FirstName    = firstName,
                LastName     = lastName,
                Street       = street,
                StreetNumber = streetNumber,
                PhoneNumber  = phoneNumber
            });
            await WebSocketConnection.SendAsync(msg);

            string responseMsg;

            try
            {
                responseMsg = ReadMessage();
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Failed to add client! {e}");
                return(null);
            }
            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(responseMsg);

            if (!(response.Data is ClientDTO clientData))
            {
                throw new ApplicationException("Provided client data object is invalid!");
            }

            return(clientData.ToIClient());
        }
Esempio n. 4
0
 public void DeserializeWebMessage_PreviouslySerializedData_ReturnsValidObjects()
 {
     foreach (KeyValuePair <WebMessageType, object> pair in SampleWebMessageData)
     {
         string jsonData = Serializer.SerializeWebMessage(pair.Key, pair.Value);
         WebMessageDTO <object> messageDto = Serializer.DeserializeWebMessage(jsonData);
         Assert.IsNotNull(messageDto);
         Assert.IsNotNull(messageDto.Data);
     }
 }
Esempio n. 5
0
        public async Task <HashSet <IProduct> > GetAllProducts()
        {
            await WebSocketConnection.SendAsync(WebSimpleMessageType.GetAllProducts.ToString());

            WebMessageDTO <object> msg = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(msg.Data is HashSet <ProductDTO> productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }
            return(new HashSet <IProduct>(productData.Select(p => p.ToIProduct())));
        }
Esempio n. 6
0
        public async Task <HashSet <IOrder> > GetAllOrders()
        {
            await WebSocketConnection.SendAsync(WebSimpleMessageType.GetAllOrders.ToString());

            WebMessageDTO <object> msg = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(msg.Data is HashSet <OrderDTO> orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }
            return(new HashSet <IOrder>(orderData.Select(o => o.ToIOrder())));
        }
Esempio n. 7
0
        public async Task <IProduct> GetProduct(uint id)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetProduct, id);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is ProductDTO productData))
            {
                throw new ApplicationException("Provided product data object is invalid!");
            }

            return(productData.ToIProduct());
        }
Esempio n. 8
0
        public async Task <IOrder> GetOrder(uint id)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetOrder, id);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is OrderDTO orderData))
            {
                throw new ApplicationException("Provided order data object is invalid!");
            }

            return(orderData.ToIOrder());
        }
Esempio n. 9
0
        public async Task <IClient> GetClient(string username)
        {
            string msg = WebSerializer.SerializeWebMessage(WebMessageType.GetClient, username);
            await WebSocketConnection.SendAsync(msg);

            WebMessageDTO <object> response = WebSerializer.DeserializeWebMessage(ReadMessage());

            if (!(response.Data is ClientDTO clientData))
            {
                throw new ApplicationException("Provided client data object is invalid!");
            }

            return(clientData.ToIClient());
        }
Esempio n. 10
0
        public void OnMessage(string message)
        {
            Debug.WriteLine($"{WebSocketConnection}> {message}");

            if (WebSerializer.TryParseRequest(message, out WebSimpleMessageType simpleMessage))
            {
                switch (simpleMessage)
                {
                case WebSimpleMessageType.Failure:
                case WebSimpleMessageType.Success:
                    MessageQueue.Enqueue(message);
                    NewMessageEvent.Set();
                    break;

                default:
                    // the server will not ask the client for data
                    throw new NotImplementedException();
                }
            }
            else
            {
                WebMessageDTO <object> msgDto = WebSerializer.DeserializeWebMessage(message);
                switch (msgDto.MessageType)
                {
                case WebMessageType.ProvideAllClients:
                case WebMessageType.ProvideAllProducts:
                case WebMessageType.ProvideAllOrders:
                case WebMessageType.ProvideClient:
                case WebMessageType.ProvideProduct:
                case WebMessageType.ProvideOrder:
                {
                    MessageQueue.Enqueue(message);
                    NewMessageEvent.Set();
                    break;
                }

                case WebMessageType.OrderSent:
                {
                    OrderSent orderSent = new OrderSent((msgDto.Data as OrderDTO)?.ToIOrder());
                    foreach (IObserver <OrderSent> observer in OrderSentObservers)
                    {
                        observer.OnNext(orderSent);
                    }

                    break;
                }

                case WebMessageType.AddClient:
                {
                    DataChanged <IClient> change =
                        new DataChanged <IClient>(DataChangedAction.Add,
                                                  new List <IClient> {
                            (msgDto.Data as ClientDTO)?.ToIClient()
                        });
                    foreach (IObserver <DataChanged <IClient> > observer in ClientObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.UpdateClient:
                {
                    DataChanged <IClient> change =
                        new DataChanged <IClient>(DataChangedAction.Update,
                                                  new List <IClient> {
                            (msgDto.Data as ClientDTO)?.ToIClient()
                        });
                    foreach (IObserver <DataChanged <IClient> > observer in ClientObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.RemoveClient:
                {
                    DataChanged <IClient> change =
                        new DataChanged <IClient>(DataChangedAction.Remove,
                                                  new List <IClient> {
                            (msgDto.Data as ClientDTO)?.ToIClient()
                        });
                    foreach (IObserver <DataChanged <IClient> > observer in ClientObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.AddProduct:
                {
                    DataChanged <IProduct> change =
                        new DataChanged <IProduct>(DataChangedAction.Add,
                                                   new List <IProduct> {
                            (msgDto.Data as ProductDTO)?.ToIProduct()
                        });
                    foreach (IObserver <DataChanged <IProduct> > observer in ProductObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.UpdateProduct:
                {
                    DataChanged <IProduct> change =
                        new DataChanged <IProduct>(DataChangedAction.Update,
                                                   new List <IProduct> {
                            (msgDto.Data as ProductDTO)?.ToIProduct()
                        });
                    foreach (IObserver <DataChanged <IProduct> > observer in ProductObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.RemoveProduct:
                {
                    DataChanged <IProduct> change =
                        new DataChanged <IProduct>(DataChangedAction.Remove,
                                                   new List <IProduct> {
                            (msgDto.Data as ProductDTO)?.ToIProduct()
                        });
                    foreach (IObserver <DataChanged <IProduct> > observer in ProductObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.AddOrder:
                {
                    DataChanged <IOrder> change =
                        new DataChanged <IOrder>(DataChangedAction.Add,
                                                 new List <IOrder> {
                            (msgDto.Data as OrderDTO)?.ToIOrder()
                        });
                    foreach (IObserver <DataChanged <IOrder> > observer in OrderObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.UpdateOrder:
                {
                    DataChanged <IOrder> change =
                        new DataChanged <IOrder>(DataChangedAction.Update,
                                                 new List <IOrder> {
                            (msgDto.Data as OrderDTO)?.ToIOrder()
                        });
                    foreach (IObserver <DataChanged <IOrder> > observer in OrderObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.RemoveOrder:
                {
                    DataChanged <IOrder> change =
                        new DataChanged <IOrder>(DataChangedAction.Remove,
                                                 new List <IOrder> {
                            (msgDto.Data as OrderDTO)?.ToIOrder()
                        });
                    foreach (IObserver <DataChanged <IOrder> > observer in OrderObservers)
                    {
                        observer.OnNext(change);
                    }

                    break;
                }

                case WebMessageType.Error:
                {
                    string errorMsg = msgDto.Data as string;
                    Debug.WriteLine($"The server has encountered an exception! {errorMsg}");
                    break;
                }
                }
            }
        }
Esempio n. 11
0
        private async Task ProcessClientMessage(WebSocketConnection connection, string message)
        {
            Console.WriteLine($"{connection}> {message}");
            if (WebSerializer.TryParseRequest(message, out WebSimpleMessageType msgType))
            {
                switch (msgType)
                {
                case WebSimpleMessageType.GetAllClients:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllClients,
                                                          new HashSet <ClientDTO>(
                                                              (await DataRepository.GetAllClients())
                                                              .Select(c => new ClientDTO(c))));
                    await connection.SendAsync(response);

                    break;
                }

                case WebSimpleMessageType.GetAllProducts:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllProducts,
                                                          new HashSet <ProductDTO>(
                                                              (await DataRepository.GetAllProducts())
                                                              .Select(p => new ProductDTO(p))));
                    await connection.SendAsync(response);

                    break;
                }

                case WebSimpleMessageType.GetAllOrders:
                {
                    string response =
                        WebSerializer.SerializeWebMessage(WebMessageType.ProvideAllOrders,
                                                          new HashSet <OrderDTO>(
                                                              (await DataRepository.GetAllOrders())
                                                              .Select(o => new OrderDTO(o))));
                    await connection.SendAsync(response);

                    break;
                }
                }
            }
            else
            {
                try
                {
                    WebMessageDTO <object> msgDto = WebSerializer.DeserializeWebMessage(message);
                    switch (msgDto.MessageType)
                    {
                    case WebMessageType.AddClient:
                    {
                        if (msgDto.Data is ClientDTO clt)
                        {
                            IClient client = await DataRepository.CreateClient(
                                clt.Username, clt.FirstName, clt.LastName,
                                clt.Street, clt.StreetNumber, clt.PhoneNumber);

                            if (client == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                ClientDTO newDto = new ClientDTO(client);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideClient, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddClient, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateClient:
                    {
                        bool result = false;
                        if (msgDto.Data is ClientDTO clt)
                        {
                            try
                            {
                                result = await DataRepository.Update(clt.ToIClient());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateClient, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveClient:
                    {
                        bool result = false;
                        if (msgDto.Data is ClientDTO clt)
                        {
                            try
                            {
                                result = await DataRepository.RemoveClient(clt.ToIClient());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveClient, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.AddProduct:
                    {
                        if (msgDto.Data is ProductDTO prd)
                        {
                            IProduct product = await DataRepository.CreateProduct(
                                prd.Name, prd.Price, prd.ProductType);

                            if (product == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                ProductDTO newDto = new ProductDTO(product);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideProduct, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddProduct, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateProduct:
                    {
                        bool result = false;
                        if (msgDto.Data is ProductDTO prd)
                        {
                            try
                            {
                                result = await DataRepository.Update(prd.ToIProduct());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateProduct, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveProduct:
                    {
                        bool result = false;
                        if (msgDto.Data is ProductDTO prd)
                        {
                            try
                            {
                                result = await DataRepository.RemoveProduct(prd.ToIProduct());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveProduct, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.AddOrder:
                    {
                        if (msgDto.Data is OrderDTO ord)
                        {
                            IOrder order = await DataRepository.CreateOrder(
                                ord.ClientUsername, ord.OrderDate,
                                ord.ProductIdQuantityMap, ord.DeliveryDate);

                            if (order == null)
                            {
                                await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                            }
                            else
                            {
                                OrderDTO newDto = new OrderDTO(order);
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.ProvideOrder, newDto));

                                await ServerWebSocketConnection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.AddOrder, newDto));
                            }
                        }
                        else
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());
                        }
                        break;
                    }

                    case WebMessageType.UpdateOrder:
                    {
                        bool result = false;
                        if (msgDto.Data is OrderDTO ord)
                        {
                            try
                            {
                                result = await DataRepository.Update(ord.ToIOrder());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.UpdateOrder, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.RemoveOrder:
                    {
                        bool result = false;
                        if (msgDto.Data is OrderDTO ord)
                        {
                            try
                            {
                                result = await DataRepository.RemoveOrder(ord.ToIOrder());
                            }
                            catch (Exception e)
                            {
                                await connection.SendAsync(
                                    WebSerializer.SerializeWebMessage(WebMessageType.Error, e.ToString()));
                            }
                        }
                        await connection.SendAsync(result
                                                   ?WebSimpleMessageType.Success.ToString()
                                                       : WebSimpleMessageType.Failure.ToString());

                        if (result)
                        {
                            await ServerWebSocketConnection.SendAsync(
                                WebSerializer.SerializeWebMessage(WebMessageType.RemoveOrder, msgDto.Data));
                        }

                        break;
                    }

                    case WebMessageType.GetClient:
                    {
                        if (!(msgDto.Data is string username))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IClient client = await DataRepository.GetClient(username);

                        if (client == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideClient,
                                                                            new ClientDTO(client));

                        await connection.SendAsync(response);

                        break;
                    }

                    case WebMessageType.GetProduct:
                    {
                        if (!(msgDto.Data is uint id))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IProduct product = await DataRepository.GetProduct(id);

                        if (product == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideProduct,
                                                                            new ProductDTO(product));

                        await connection.SendAsync(response);

                        break;
                    }

                    case WebMessageType.GetOrder:
                    {
                        if (!(msgDto.Data is uint id))
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }
                        IOrder order = await DataRepository.GetOrder(id);

                        if (order == null)
                        {
                            await connection.SendAsync(WebSimpleMessageType.Failure.ToString());

                            break;
                        }

                        string response = WebSerializer.SerializeWebMessage(WebMessageType.ProvideOrder,
                                                                            new OrderDTO(order));

                        await connection.SendAsync(response);

                        break;
                    }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to parse message '{message}' from a client! {e}");
                }
            }
        }