Esempio n. 1
0
        private void HandleInstrumentAdditionRequest()
        {
            using (var ms = new MemoryStream())
            {
                var buffer     = _socket.ReceiveFrameBytes();
                var instrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                _logger.Info($"Instruments Server: Received instrument addition request. Instrument: {instrument}");

                Instrument addedInstrument;

                try
                {
                    addedInstrument = _instrumentManager.AddInstrument(instrument);
                }
                catch (Exception ex)
                {
                    addedInstrument = null;

                    _logger.Error($"Instruments Server: Instrument addition error: {ex.Message}");
                }

                _socket.SendMoreFrame(addedInstrument != null ? MessageType.Success : MessageType.Error);

                _socket.SendFrame(MyUtils.ProtoBufSerialize(addedInstrument, ms));
            }
        }
Esempio n. 2
0
        private void SocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            var hasMore = false;
            var request = string.Empty;

            lock (_socketLock) {
                var receiveResult = _socket?.TryReceiveFrameString(out request, out hasMore);

                if (!receiveResult.HasValue || !receiveResult.Value || string.IsNullOrEmpty(request))
                {
                    return;
                }
            }

            var instruments = new List <Instrument>();

            using (var ms = new MemoryStream()) {
                // If the request is for a search, receive the instrument w/ the search parameters and pass it to the searcher
                if (request == "SEARCH" && hasMore)
                {
                    var buffer           = _socket.ReceiveFrameBytes();
                    var searchInstrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                    _logger.Info($"Instruments Server: Received search request: {searchInstrument}");

                    try {
                        instruments = _instrumentManager.FindInstruments(null, searchInstrument);
                    }
                    catch (Exception ex) {
                        _logger.Error($"Instruments Server: Instrument search error: {ex.Message}");
                    }
                }
                else if (request == "ALL") // If the request is for all the instruments, we don't need to receive anything else
                {
                    _logger.Info("Instruments Server: received request for list of all instruments.");

                    try {
                        instruments = _instrumentManager.FindInstruments();
                    }
                    catch (Exception ex) {
                        _logger.Error($"Instruments Server: Instrument search error: {ex.Message}");
                    }
                }
                else if (request == "ADD" && hasMore) // Request to add instrument
                {
                    var buffer     = _socket.ReceiveFrameBytes();
                    var instrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                    _logger.Info($"Instruments Server: Received instrument addition request. Instrument: {instrument}");

                    Instrument addedInstrument;

                    try {
                        addedInstrument = _instrumentManager.AddInstrument(instrument);
                    }
                    catch (Exception ex) {
                        addedInstrument = null;

                        _logger.Error($"Instruments Server: Instrument addition error: {ex.Message}");
                    }

                    _socket.SendMoreFrame(addedInstrument != null ? "SUCCESS" : "FAILURE");

                    _socket.SendFrame(MyUtils.ProtoBufSerialize(addedInstrument, ms));

                    return;
                }
                else // No request = loop again
                {
                    return;
                }

                var uncompressed = MyUtils.ProtoBufSerialize(instruments, ms); // Serialize the list of instruments

                ms.Read(uncompressed, 0, (int)ms.Length);                      // Get the uncompressed data

                var result = LZ4Codec.Encode(uncompressed, 0, (int)ms.Length); // Compress it
                // Before we send the result we must send the length of the uncompressed array, because it's needed for decompression
                _socket.SendMoreFrame(BitConverter.GetBytes(uncompressed.Length));
                // Then finally send the results
                _socket.SendFrame(result);
            }
        }
Esempio n. 3
0
        public InstrumentModule(IInstrumentSource instrumentRepo, IDataStorage dataStorage) : base("/instruments")
        {
            this.RequiresAuthentication();

            Get["/", true] = async(_, token) => await instrumentRepo.FindInstruments().ConfigureAwait(false);

            Get["/{Id:int}", true] = async(parameters, token) =>
            {
                //Instrument by ID
                var id         = (int)parameters.Id;
                var instrument = (await instrumentRepo.FindInstruments(x => x.ID == id).ConfigureAwait(false)).FirstOrDefault();

                if (instrument == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                return(instrument);
            };

            Get["/search", true] = async(_, token) =>
            {
                //Search using an instrument object
                var inst = this.Bind <Instrument>();
                if (inst == null)
                {
                    return(HttpStatusCode.BadRequest);
                }

                return(await instrumentRepo.FindInstruments(inst).ConfigureAwait(false));
            };

            Get["/predsearch", true] = async(parameters, token) =>
            {
                //Search using a predicate
                var predReq = this.Bind <PredicateSearchRequest>();
                if (predReq == null)
                {
                    return(HttpStatusCode.BadRequest);
                }

                //Deserialize LINQ expression and pass it to the instrument manager
                Expression <Func <Instrument, bool> > expression;
                try
                {
                    expression = predReq.Filter;
                }
                catch (Exception ex)
                {
                    return(Negotiate
                           .WithModel(new ValidationErrorResponse("Malformed predicate: " + ex.Message))
                           .WithStatusCode(HttpStatusCode.BadRequest));
                }
                var instruments = await instrumentRepo.FindInstruments(expression).ConfigureAwait(false);

                return(instruments);
            };

            Post["/", true] = async(parameters, token) =>
            {
                Instrument instrument = this.BindAndValidate <Instrument>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                var addedInstrument = await instrumentRepo.AddInstrument(instrument);

                return(addedInstrument);
            };

            Put["/", true] = async(parameters, token) =>
            {
                var instrument = this.BindAndValidate <Instrument>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                //find it
                Instrument instrumentFromDB = (await instrumentRepo.FindInstruments(x => x.ID == instrument.ID).ConfigureAwait(false)).FirstOrDefault();
                if (instrumentFromDB == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                //update it
                await instrumentRepo.UpdateInstrument(instrumentFromDB, instrument).ConfigureAwait(false);

                return(instrumentFromDB);
            };

            Delete["/{Id:int}", true] = async(parameters, token) =>
            {
                int id         = parameters.Id;
                var instrument = (await instrumentRepo.FindInstruments(x => x.ID == id).ConfigureAwait(false)).FirstOrDefault();

                if (instrument == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                await instrumentRepo.RemoveInstrument(instrument, dataStorage).ConfigureAwait(false);

                return(instrument);
            };
        }
Esempio n. 4
0
        void _socket_ReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            var ms = new MemoryStream();
            List <Instrument> instruments;
            bool   hasMore;
            string request = _socket.ReceiveString(SendReceiveOptions.DontWait, out hasMore);

            if (request == null)
            {
                return;
            }

            //if the request is for a search, receive the instrument w/ the search parameters and pass it to the searcher
            if (request == "SEARCH" && hasMore)
            {
                byte[] buffer           = _socket.Receive();
                var    searchInstrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                Log(LogLevel.Info, string.Format("Instruments Server: Received search request: {0}",
                                                 searchInstrument));

                try
                {
                    instruments = _instrumentManager.FindInstruments(null, searchInstrument);
                }
                catch (Exception ex)
                {
                    Log(LogLevel.Error, string.Format("Instruments Server: Instrument search error: {0}",
                                                      ex.Message));
                    instruments = new List <Instrument>();
                }
            }
            else if (request == "ALL") //if the request is for all the instruments, we don't need to receive anything else
            {
                Log(LogLevel.Info, "Instruments Server: received request for list of all instruments.");
                instruments = _instrumentManager.FindInstruments();
            }
            else if (request == "ADD" && hasMore) //request to add instrument
            {
                byte[] buffer     = _socket.Receive();
                var    instrument = MyUtils.ProtoBufDeserialize <Instrument>(buffer, ms);

                Log(LogLevel.Info, string.Format("Instruments Server: Received instrument addition request. Instrument: {0}",
                                                 instrument));

                Instrument addedInstrument;
                try
                {
                    addedInstrument = _instrumentManager.AddInstrument(instrument);
                }
                catch (Exception ex)
                {
                    addedInstrument = null;
                    Log(LogLevel.Error, string.Format("Instruments Server: Instrument addition error: {0}",
                                                      ex.Message));
                }
                _socket.SendMore(addedInstrument != null ? "SUCCESS" : "FAILURE");

                _socket.Send(MyUtils.ProtoBufSerialize(addedInstrument, ms));

                return;
            }
            else //no request = loop again
            {
                return;
            }

            byte[] uncompressed = MyUtils.ProtoBufSerialize(instruments, ms); //serialize the list of instruments
            ms.Read(uncompressed, 0, (int)ms.Length);                         //get the uncompressed data
            byte[] result = LZ4Codec.Encode(uncompressed, 0, (int)ms.Length); //compress it

            //before we send the result we must send the length of the uncompressed array, because it's needed for decompression
            _socket.SendMore(BitConverter.GetBytes(uncompressed.Length));

            //then finally send the results
            _socket.Send(result);
        }