public static T ToObject <T>(this IDictionary <string, object> source)
            where T : class, new()
        {
            var tmpObject     = new T();
            var tmpObjectType = tmpObject.GetType();

            foreach (var item in source)
            {
                try
                {
                    var propertyInfo = tmpObjectType.GetProperty(item.Key);

                    if (propertyInfo == null)
                    {
                        continue;
                    }
                    if (propertyInfo.PropertyType == typeof(MrnTypeEnum))
                    {
                        propertyInfo.SetValue(tmpObject,
                                              Convert.ChangeType((MrnTypeEnum)Enum.Parse(typeof(MrnTypeEnum), (string)item.Value, true), propertyInfo.PropertyType), null);
                    }
                    else if (propertyInfo.PropertyType == typeof(byte[]))
                    {
                        var tmpValue = (item.Value == null) ? null : MarketDataUtils.StringToByteArray((string)item.Value);
                        propertyInfo.SetValue(tmpObject,
                                              Convert.ChangeType(tmpValue, propertyInfo.PropertyType), null);
                    }
                    else
                    {
                        propertyInfo.SetValue(tmpObject,
                                              Convert.ChangeType(item.Value, propertyInfo.PropertyType), null);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message}");
                }
            }

            return(tmpObject);
        }
示例#2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting MRN Websocket Consumer app. Press Ctrl+C to exit.\n");
            var websocket = new WebsocketConnectionClient(Clientname, WebsocketUri, "tr_json2");

            websocket.Cts = new CancellationTokenSource();
            var mrnmanager = new MrnStoryManager(websocket);

            mrnmanager.MRN_STREAM_ID = 3;
            mrnmanager.MessageEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process MRN Message Events **********************");
                Console.WriteLine($"TimeStamp:{e.TimeStamp}");
                Console.WriteLine($"Received {e.Data.MsgType} {e.TimeStamp}\n");
                Console.WriteLine($"Active Date:{e.Data.ACTIV_DATE}");
                Console.WriteLine($"MRN_TYPE:{e.Data.MRN_TYPE}");
                Console.WriteLine($"Context ID:{e.Data.CONTEXT_ID}");
                Console.WriteLine($"Prod Perm:{e.Data.PROD_PERM}");
                Console.WriteLine($"Fragment Count={e.Data.FRAG_NUM} Total Size={e.Data.TOT_SIZE} bytes");
                if (e.Data.Story != null)
                {
                    Console.WriteLine(e.Data.Story.ToJson());
                }
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };
            mrnmanager.ErrorEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process MRN Error Events **********************");
                Console.WriteLine($"TimeStamp:{e.TimeStamp}");
                Console.WriteLine($"{e.ErrorMessage}");
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };
            mrnmanager.StatusEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process MRN Status Events **********************");
                Console.WriteLine($"Received {e.Status.MsgType} {e.TimeStamp}");
                Console.WriteLine($"Stream State:{e.Status.State.Stream}");
                Console.WriteLine($"Data State:{e.Status.State.Data}");
                Console.WriteLine($"State Code:{e.Status.State.Code}");
                Console.WriteLine($"Status Text:{e.Status.State.Text}");
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };
            mrnmanager.LoginMessageEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process Login Message Events **********************");
                Console.WriteLine($"{e.TimeStamp}  received {e.Message.MsgType}");
                switch (e.Message.MsgType)
                {
                case MessageTypeEnum.Refresh:
                {
                    var message = (RefreshMessage)e.Message;
                    Console.WriteLine($"Login name:{message.Key.Name.FirstOrDefault()}");
                    Console.WriteLine(
                        $"Login Refresh stream:{message.State.Stream} state:{message.State.Data} code:{message.State.Code} status text:{message.State.Text}");
                }
                break;

                case MessageTypeEnum.Status:
                {
                    var message = (StatusMessage)e.Message;
                    Console.WriteLine($"Login name:{message.Key.Name.FirstOrDefault()}");
                    Console.WriteLine(
                        $"Login Status stream:{message.State.Stream} state:{message.State.Data} code:{message.State.Code} status text:{message.State.Text}");
                    if (message.State.Stream == StreamStateEnum.Closed ||
                        message.State.Stream == StreamStateEnum.ClosedRecover)
                    {
                        b_cancel = true;
                    }
                }
                break;
                }
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };
            websocket.ErrorEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process Websocket Error Events **********************");
                Console.WriteLine($"OnConnectionError {e.TimeStamp} {e.ClientWebSocketState} {e.ErrorDetails}");
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };

            websocket.ConnectionEvent += (sender, e) =>
            {
                Console.WriteLine("******************* Process Websocket Connection Events **********************");
                Console.WriteLine($"OnConnection Event Received:{MarketDataUtils.TimeStampToString(e.TimeStamp)}");

                Console.WriteLine($"Connection State:{e.State}");
                Console.WriteLine($"Message:{e.StatusText}");
                if (e.State == WebSocketState.Open)
                {
                    mrnmanager.SendLogin(DACS_User, Login_Position, AppId, 1).GetAwaiter().GetResult();
                }
                Console.WriteLine("*********************************************************************");
                Console.WriteLine();
            };
            Console.CancelKeyPress += (sender, e) =>
            {
                websocket.Stop = true;
                b_cancel       = true;
            };
            websocket.Run().GetAwaiter().GetResult();
            while (!b_cancel)
            {
                ;
            }

            Console.WriteLine("Quit the app");
        }
示例#3
0
        private bool ProcessFieldData(IDictionary <string, object> Fields)
        {
            var mrnData = Fields.ToObject <MrnStoryData>();

            mrnData.MsgType = MessageTypeEnum.Update;
            var newUpdateByteArray    = mrnData.FRAGMENT ?? throw new ArgumentNullException("mrnData.FRAGMENT");
            var newUpdateFragmentSize = (int?)newUpdateByteArray?.Length ?? 0;

            if (mrnData.FRAG_NUM == 1 && mrnData.TOT_SIZE > 0)
            {
                //Shrink FRAGMENT size to TOT_SIZE
                mrnData.FRAGMENT = new byte[mrnData.TOT_SIZE];
                Buffer.BlockCopy(newUpdateByteArray ?? throw new InvalidOperationException(), 0,
                                 mrnData.FRAGMENT, 0, (int)newUpdateFragmentSize);
                mrnData.FragmentSize = newUpdateFragmentSize;
                _mrnDataList.Add(UpdateCount, mrnData);
            }
            else if (mrnData.FRAG_NUM > 1)
            {
                if (_mrnDataList[UpdateCount].GUID == mrnData.GUID)
                {
                    var tmpByteArray    = _mrnDataList[UpdateCount].FRAGMENT;
                    var tmpTotalSize    = _mrnDataList[UpdateCount].TOT_SIZE;
                    var tmpFragmentSize = _mrnDataList[UpdateCount].FragmentSize;

                    _mrnDataList[UpdateCount]              = mrnData;
                    _mrnDataList[UpdateCount].FRAGMENT     = tmpByteArray;
                    _mrnDataList[UpdateCount].TOT_SIZE     = tmpTotalSize;
                    _mrnDataList[UpdateCount].FragmentSize = tmpFragmentSize;

                    Buffer.BlockCopy(newUpdateByteArray, 0,
                                     _mrnDataList[UpdateCount].FRAGMENT,
                                     (int)_mrnDataList[UpdateCount].FragmentSize, (int)newUpdateFragmentSize);

                    // Calculate current Fragment Size
                    _mrnDataList[UpdateCount].FragmentSize += newUpdateFragmentSize;
                }
                else
                {
                    var msg =
                        $"Cannot find previous update with the same GUID {mrnData.GUID}. This update will be skipped.";
                    RaiseErrorEvent(DateTime.Now, msg);
                    UpdateCount++;
                }
            }

            // Check if the update contains complete MRN Story
            if (_mrnDataList[UpdateCount].IsCompleted)
            {
                _mrnDataList[UpdateCount].JsonData = MarketDataUtils
                                                     .UnpackByteToJsonString(_mrnDataList[UpdateCount].FRAGMENT).GetAwaiter().GetResult();
                RaiseMrnMessageEvent(DateTime.Now, _mrnDataList[UpdateCount]);
                UpdateCount++;
                return(true);
            }
            else
            {
                if (_mrnDataList[UpdateCount].FragmentSize > _mrnDataList[UpdateCount].TOT_SIZE)
                {
                    var msg = $"Received message with GUID={_mrnDataList[UpdateCount].GUID} has a size greater than total message size. This update will be skipped.";
                    Console.WriteLine(msg);
                    RaiseErrorEvent(DateTime.Now, msg);
                    UpdateCount++;
                }
            }

            return(false);
        }
示例#4
0
        private static void Main(string[] args)
        {
            var appConfig = new Config();

            if (!ShowsConfigCommand(args, ref appConfig))
            {
                return;
            }

            WebsocketUri   = new Uri(appConfig.WsServer);
            DACS_User      = appConfig.DacsUserName;
            AppId          = appConfig.AppId;
            Login_Position = appConfig.DacsPosition;
            chainRic       = appConfig.ChainRic;
            useSequential  = appConfig.SequentialMode;
            if (appConfig.ChainRic.Contains(','))
            {
                Out($"{appConfig.ChainRic} is invalid RIC it contains ','");
                return;
            }

            if (string.IsNullOrWhiteSpace(appConfig.ChainRic))
            {
                Out($"{appConfig.ChainRic} contains whitespace");
                return;
            }

            stopwatch.Reset();

            Out("Starting Chain Extractor application. Press Ctrl+C to cancel operation.\n");
            var websocket = new WebsocketConnectionClient(Clientname, WebsocketUri, "tr_json2")
            {
                Cts = new CancellationTokenSource()
            };

            var chainManager = new ChainExpander.ChainExpander(websocket)
            {
                OverrideStopIndexValue = appConfig.StopIndex,
                MaxBatchSize           = appConfig.MaxBatchSize,
                Verbose   = appConfig.Verbose,
                PrintJson = appConfig.PrintJson
            };

            chainManager.OnExtractionCompleteEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                if (!e.IsSuccess)
                {
                    consoleOutputMsg.Append($"{e.Message}\n\n");
                }

                SubscribedChainList.AddRange(e.ChainList);

                var tempList = e.ItemList.Where(ChainUtils.IsChainRIC).ToList();
                AvailableChainList.AddRange(tempList);
                if (tempList.Any())
                {
                    consoleOutputMsg.Append($"\nReceived {tempList.Count()} underlying Chain RICs from the list\n\n");
                    consoleOutputMsg.Append(string.Join("\n", e.ItemList.Where(ChainUtils.IsChainRIC)));
                    AvailableChainList.AddRange((tempList));
                }

                var tempItemList = e.ItemList.Where(item => !ChainUtils.IsChainRIC(item)).ToList();
                if (tempItemList.Any())
                {
                    CompleteItemList.AddRange(tempItemList);
                }


                if (AvailableChainList.Any())
                {
                    var firstItem = AvailableChainList.First();
                    AvailableChainList.Remove(firstItem);
                    chainManager.RunExtraction(firstItem, appConfig.SequentialRecursiveMode).GetAwaiter().GetResult();
                }
                else
                {
                    stopwatch.Stop();
                    consoleOutputMsg.Append($"\nOperation Completed in {stopwatch.ElapsedMilliseconds} MS.\n");
                    if (SubscribedChainList.Any())
                    {
                        consoleOutputMsg.Append(
                            $"\nBelow is a list of Chain RIC application has requested from the server\n\n");
                        consoleOutputMsg.Append($"{string.Join(",", SubscribedChainList)}\n\n");
                    }

                    if (CompleteItemList.Any())
                    {
                        consoleOutputMsg.Append(
                            $"\nReceived {CompleteItemList.Count()} constituents/instruments from the Chains\n\n");
                        consoleOutputMsg.Append(string.Join("\n",
                                                            CompleteItemList.Where(item => !ChainUtils.IsChainRIC(item)).OrderBy(ric => ric)));
                    }

                    consoleOutputMsg.Append("\n");
                    Out(consoleOutputMsg.ToString(), true);
                    if (!string.IsNullOrEmpty(appConfig.OutputFilename))
                    {
                        if (SaveListToFile(appConfig.OutputFilename,
                                           CompleteItemList.Where(item => !ChainUtils.IsChainRIC(item)).OrderBy(ric => ric).ToList()).GetAwaiter().GetResult())
                        {
                            Console.WriteLine($"Write RIC list to {appConfig.OutputFilename} completed.");
                        }
                    }
                    chainManager.CloseLogin().GetAwaiter().GetResult();
                    websocket.Stop = true;
                }
            };
            chainManager.OnExtractionErrorEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                consoleOutputMsg.Append("******************* Process Error Events **********************\n");
                consoleOutputMsg.Append($"TimeStamp:{e.TimeStamp}\n");
                consoleOutputMsg.Append($"{e.ErrorMessage}\n");
                consoleOutputMsg.Append("*********************************************************************\n");
                Out(consoleOutputMsg.ToString(), appConfig.Verbose);
            };
            chainManager.OnExtractionStatusEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                consoleOutputMsg.Append("******************* Process Market Data Status Events **********************\n");
                consoleOutputMsg.Append($"Received {e.Status.MsgType} {e.TimeStamp}\n");
                consoleOutputMsg.Append($"Stream State:{e.Status.State.Stream}\n");
                if (e.Status.Key != null)
                {
                    consoleOutputMsg.Append($"Item Name:{e.Status.Key.Name.FirstOrDefault()}\n");
                }
                consoleOutputMsg.Append($"Data State:{e.Status.State.Data}\n");
                consoleOutputMsg.Append($"State Code:{e.Status.State.Code}\n");
                consoleOutputMsg.Append($"Status Text:{e.Status.State.Text}\n");
                consoleOutputMsg.Append("*********************************************************************\n");
                Out(consoleOutputMsg.ToString(), appConfig.Verbose);
            };
            chainManager.LoginMessageEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                consoleOutputMsg.Append("******************* Process Login Message Events **********************\n");
                consoleOutputMsg.Append($"{e.TimeStamp}  received {e.Message.MsgType}\n");
                switch (e.Message.MsgType)
                {
                case MessageTypeEnum.Refresh:
                {
                    var message = (RefreshMessage)e.Message;
                    consoleOutputMsg.Append($"Login name:{message.Key.Name.FirstOrDefault()}\n");

                    consoleOutputMsg.Append(
                        $"Login Refresh stream:{message.State.Stream} state:{message.State.Data} code:{message.State.Code} status text:{message.State.Text}\n");
                    consoleOutputMsg.Append("*********************************************************************\n");
                    consoleOutputMsg.Append("\n");
                    Out(consoleOutputMsg.ToString(), appConfig.Verbose);
                    if (message.State.Stream == StreamStateEnum.Open &&
                        message.State.Data != DataStateEnum.Suspect)
                    {
                        stopwatch.Start();
                        chainManager.RunExtraction(chainRic, useSequential).GetAwaiter().GetResult();
                    }
                }
                break;

                case MessageTypeEnum.Status:
                {
                    var message = (StatusMessage)e.Message;
                    consoleOutputMsg.Append($"Login name:{message.Key.Name.FirstOrDefault()}\n");
                    consoleOutputMsg.Append(
                        $"Login Status stream:{message.State.Stream} state:{message.State.Data} code:{message.State.Code} status text:{message.State.Text}\n");
                    consoleOutputMsg.Append("*********************************************************************\n");
                    consoleOutputMsg.Append("\n");
                    Out(consoleOutputMsg.ToString(), appConfig.Verbose);
                    if (message.State.Stream == StreamStateEnum.Closed ||
                        message.State.Stream == StreamStateEnum.ClosedRecover)
                    {
                        websocket.Stop = true;
                    }
                }
                break;
                }
            };
            websocket.ErrorEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                consoleOutputMsg.Append("******************* Process Websocket Error Events **********************\n");
                consoleOutputMsg.Append($"OnConnectionError {e.TimeStamp} {e.ClientWebSocketState} {e.ErrorDetails}\n");
                consoleOutputMsg.Append("*********************************************************************\n");
                Out(consoleOutputMsg.ToString(), true);
                websocket.Stop = true;
            };

            websocket.ConnectionEvent += (sender, e) =>
            {
                consoleOutputMsg.Clear();
                consoleOutputMsg.Append("******************* Process Websocket Connection Events **********************\n");
                consoleOutputMsg.Append($"OnConnection Event Received:{MarketDataUtils.TimeStampToString(e.TimeStamp)}\n");

                consoleOutputMsg.Append($"Connection State:{e.State}\n");
                consoleOutputMsg.Append($"Message:{e.StatusText}\n");
                if (e.State == WebSocketState.Open)
                {
                    chainManager.SendLogin(DACS_User, Login_Position, AppId, 1).GetAwaiter().GetResult();
                }
                consoleOutputMsg.Append("*********************************************************************\n");
                Out(consoleOutputMsg.ToString(), true);
            };
            Console.CancelKeyPress += (sender, e) =>
            {
                if (e.SpecialKey != ConsoleSpecialKey.ControlC)
                {
                    return;
                }
                Out("Ctrl+C Pressed");
                chainManager.CloseLogin().GetAwaiter().GetResult();
                websocket.Stop = true;
            };
            websocket.Run().GetAwaiter().GetResult();
            while (!websocket.Stop)
            {
                ;
            }

            Out("Quit the app");
        }