예제 #1
0
        public PricePublisher(IPriceService priceService, PriceServiceConfiguration configuration)
        {
            _rand = new Random();

            _priceService  = priceService;
            _configuration = configuration;

            var accessTokenRetrieverFactory = new AccessTokenRetrieverFactory();

            var tokenRetriever = accessTokenRetrieverFactory.GetToken(
                "internal",
                "idkfa",
                _configuration.Identity,
                AzurePlaygroundConstants.Auth.ClientReferenceToken,
                AzurePlaygroundConstants.Api.Trade,
                _configuration.Key
                );

            _priceHubService = SignalRServiceBuilder <Price, PriceRequest>
                               .Create()
                               .Build(new PriceRequest((p) => true), (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(tokenRetriever());
            });

            _priceHubService.Connect(Scheduler.Default, 2000);

            _cleanUp = new CompositeDisposable();
        }
예제 #2
0
        public TradeService(IUserService userService)
        {
            _repository = new List <ITrade>();

            for (var i = 0; i < 10; i++)
            {
                var trade = TradeServiceReferential.GenerateTrade();
                _repository.Add(trade);
            }

            var token = userService.Login(new Credentials()
            {
                Username = "******",
                Password = "******"
            }).Result;


            _tradeEventService = SignalRServiceBuilder <TradeEvent, TradeEventRequest>
                                 .Create()
                                 .Build(new TradeEventRequest((p) => true), (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(token.Digest);
            });

            _tradeEventService.Connect(Scheduler.Default, 1000)
            .Subscribe((tradeEvent) =>
            {
                var trade = _repository.FirstOrDefault(t => t.Id == tradeEvent.TradeId);
                if (null == trade)
                {
                    return;
                }
                trade.Status = tradeEvent.Status;
            });
        }
        public TradeServiceProxy(IUserService userService)
        {
            Task.Delay(500).ContinueWith((_) =>
            {
                var token = userService.Login(new Credentials()
                {
                    Username = "******",
                    Password = "******"
                }).Result;

                _tradeEventService = SignalRServiceBuilder <TradeEvent, TradeEventRequest>
                                     .Create()
                                     .Build(new TradeEventRequest((p) => true), (opts) =>
                {
                    opts.AccessTokenProvider = () => Task.FromResult(token.Digest);
                });

                _tradeEventService.Connect(Scheduler.Default, 0);
            });
        }
예제 #4
0
        public async Task ShouldTestSignalRClientResilientConnection()
        {
            var query = new PriceRequest((p) => p.Value > 50000);

            var service = SignalRServiceBuilder <Price, PriceRequest>
                          .Create()
                          .Build(query, (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(_traderToken.Digest);
            });

            var disposable = service.Connect(Scheduler.Default, 0)
                             .Subscribe(p =>
            {
                Assert.AreEqual("stock3", p.Asset);
                Assert.AreEqual(60000, p.Value);
            });

            await Task.Delay(100);

            while (service.Current.CurrentState != ConnectionStatus.Connected)
            {
                await Task.Delay(500);
            }

            await service.Current.Proxy.RaiseChange(new Price(Guid.NewGuid(), "stock1", 20000, DateTime.Now));

            await service.Current.Proxy.RaiseChange(new Price(Guid.NewGuid(), "stock2", 30000, DateTime.Now));

            await service.Current.Proxy.RaiseChange(new Price(Guid.NewGuid(), "stock3", 60000, DateTime.Now));


            await Task.Delay(500);

            disposable.Dispose();
            service.Disconnect();
        }
        public TradeEventListener(TradeEventServiceConfiguration configuration, IEventStoreCache <Guid, Trade> cache)
        {
            _cache = cache;

            var accessTokenRetrieverFactory = new AccessTokenRetrieverFactory();

            var tokenRetriever = accessTokenRetrieverFactory.GetToken(
                "internal",
                "idkfa",
                configuration.Identity,
                AzurePlaygroundConstants.Auth.ClientReferenceToken,
                AzurePlaygroundConstants.Api.Trade,
                configuration.Key
                );

            _tradeEventHubService = SignalRServiceBuilder <Trade, TradeEventRequest>
                                    .Create()
                                    .Build(new TradeEventRequest((p) => true), (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(tokenRetriever());
            });

            _tradeEventHubService.Connect(Scheduler.Default, 2000);
        }
예제 #6
0
        public MainViewModel()
        {
            Events = new ObservableCollection <string>();

            Trades = new ObservableCollection <TradeViewModel>();

            var configuration = AppCore.Instance.Get <AppConfiguration>();


            var refitSettings = new RefitSettings()
            {
                ContentSerializer         = new JsonContentSerializer(AppCore.Instance.Get <JsonSerializerSettings>()),
                HttpMessageHandlerFactory = () => new HttpRetryForeverMessageHandler(5000)
            };

            _tradeService = ApiServiceBuilder <ITradeService> .Build(configuration.Gateway)
                            .AddAuthorizationHeader(() =>
            {
                return(_token.AccessToken);
            })
                            .Create(refitSettings: refitSettings);



            MakeTrade = new Command(async() =>
            {
                var asset        = TradeServiceReferential.Assets.Random();
                var counterparty = TradeServiceReferential.Counterparties.Random();

                var rand = new Random();

                var request = new TradeCreationRequest()
                {
                    Asset  = asset.Name,
                    Volume = rand.Next(1, 50),
                    Way    = TradeWay.Buy
                };

                var tradeEvent = await _tradeService.CreateTrade(request);

                var trade = await _tradeService.GetTradeById(tradeEvent.TradeId);

                Notify($"{_token.User.Identity.Name} created trade {trade.EntityId} on desktop UI");
            });

            var options = new OidcClientOptions()
            {
                Authority = configuration.Identity,
                ClientId  = AzurePlaygroundConstants.Auth.ClientOpenIdNative,
                Scope     = "openid profile desk trade",
                Policy    = new Policy {
                    Discovery = new DiscoveryPolicy {
                        RequireHttps = false
                    }
                },
                RedirectUri           = "http://127.0.0.1/sample-wpf-app",
                PostLogoutRedirectUri = "http://127.0.0.1/sample-wpf-app",
                ResponseMode          = OidcClientOptions.AuthorizeResponseMode.FormPost,
                Flow    = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                Browser = new WpfEmbeddedBrowser()
            };

            _oidcClient = new OidcClient(options);

            Login = new Command(async() =>
            {
                try
                {
                    _token = await _oidcClient.LoginAsync(new IdentityModel.OidcClient.LoginRequest());
                }
                catch (Exception ex)
                {
                    Notify(ex.ToString());
                    return;
                }

                if (_token.IsError)
                {
                    var error = _token.Error == "User Cancellled" ? "The sign-in window was closed before authorization was completed." : _token.Error;
                    Notify(error);
                }
                else
                {
                    Token = _token;

                    Notify($"Logged in as { _token.User.Identity.Name}");

                    _priceEventService = SignalRServiceBuilder <Price, PriceRequest>
                                         .Create()
                                         .Build(new PriceRequest((p) => true), (opts) =>
                    {
                        opts.AccessTokenProvider = () => Task.FromResult(_token.AccessToken);
                    });

                    var priceServiceConnection = _priceEventService
                                                 .Connect(Scheduler.Default, 1000)
                                                 .Subscribe((priceEvent) =>
                    {
                        lock (_locker)
                        {
                            if (null == Application.Current.Dispatcher)
                            {
                                return;
                            }

                            foreach (var trade in Trades.Where(trade => trade.Asset == priceEvent.Asset).ToList())
                            {
                                Application.Current.Dispatcher.Invoke(() => trade.CurrentPrice = priceEvent.Value);
                            }
                        }

                        var ev = MakeEvent("PRICE", "PRICE", priceEvent.Asset, priceEvent.Value);

                        this.Notify(ev);
                    });


                    _tradeEventService = SignalRServiceBuilder <Trade, TradeEventRequest>
                                         .Create()
                                         .Build(new TradeEventRequest((p) => true), (opts) =>
                    {
                        opts.AccessTokenProvider = () => Task.FromResult(_token.AccessToken);
                    });


                    var tradeEventServiceConnection = _tradeEventService
                                                      .Connect(Scheduler.Default, 500)
                                                      .Subscribe((tradeEvent) =>
                    {
                        lock (_locker)
                        {
                            if (null == Application.Current.Dispatcher)
                            {
                                return;
                            }

                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                var trade = Trades.FirstOrDefault(t => t.Id == tradeEvent.EntityId);

                                if (null == trade)
                                {
                                    Trades.Add(new TradeViewModel(tradeEvent));
                                }
                                else
                                {
                                    trade.ApplyChange(tradeEvent);
                                }
                            });
                        }

                        this.Notify(MakeEvent("TRADE", _tradeEventService.Current.Endpoint, tradeEvent.EntityId, tradeEvent.EntityId));
                    });



                    _cleanup.Add(priceServiceConnection);
                    //_cleanup.Add(tradeEventServiceConnection);

                    if (null == Application.Current.Dispatcher)
                    {
                        return;
                    }

                    await Application.Current.Dispatcher.Invoke(async() =>
                    {
                        var trades = await _tradeService.GetAllTrades();

                        foreach (var trade in trades)
                        {
                            var vm = new TradeViewModel(trade);
                            Trades.Add(vm);
                        }

                        Notify($"Fetched {trades.Count()} trade(s)");
                    });
                }
            }, () => Token == null);


            Dispatcher.CurrentDispatcher.ShutdownStarted += (s, e) =>
            {
                _cleanup.Dispose();
            };

            //Logout = new Command(async() =>
            //{

            //    try
            //    {
            //        var request = new LogoutRequest
            //        {
            //            IdTokenHint = Token.IdentityToken
            //        };

            //        await _oidcClient.LogoutAsync(request);

            //        Token = null;

            //        Notify($"Logged out");


            //    }
            //    catch (Exception ex)
            //    {
            //        Notify(ex.ToString());
            //        return;
            //    }
            //});
        }
        public MainViewModel()
        {
            Events = new ObservableCollection <string>();

            _authService = ApiServiceBuilder <IUserService>
                           .Build(TradeServiceReferential.ServiceHost)
                           .Create();

            _userToken = _authService.Login(new Credentials()
            {
                Username = "******",
                Password = "******"
            }).Result;

            AppCore.Instance.ObjectProvider.Configure(config => config.For <TradeServiceToken>().Use(_userToken));

            _tradeService = ApiServiceBuilder <ITradeService> .Build(TradeServiceReferential.ServiceHost)
                            .AddAuthorizationHeader(() => _userToken.Digest)
                            .Create();

            _priceEventService = SignalRServiceBuilder <Price, PriceRequest>
                                 .Create()
                                 .Build(new PriceRequest((p) => true), (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(_userToken.Digest);
            });

            _priceEventService
            .Connect(Scheduler.Default, 1000)
            .Subscribe((priceEvent) =>
            {
                foreach (var trade in Trades.Where(trade => trade.Asset == priceEvent.Asset).ToList())
                {
                    Application.Current.Dispatcher.Invoke(() => trade.CurrentPrice = priceEvent.Value);
                }

                var ev = MakeEvent("PRICE", "PRICE", priceEvent.Asset, priceEvent.Value);
                this.Notify(ev);
            });


            _tradeEventService = SignalRServiceBuilder <TradeEvent, TradeEventRequest>
                                 .Create()
                                 .Build(new TradeEventRequest((p) => true), (opts) =>
            {
                opts.AccessTokenProvider = () => Task.FromResult(_userToken.Digest);
            });

            _tradeEventService
            .Connect(Scheduler.Default, 500)
            .Subscribe((tradeEvent) =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    var trade = Trades.FirstOrDefault(t => t.Id == tradeEvent.TradeId);
                    if (null == trade)
                    {
                        return;
                    }
                    trade.Status = tradeEvent.Status;
                });

                this.Notify(MakeEvent("TRADE", _tradeEventService.Current.Endpoint, tradeEvent.TradeId, tradeEvent.Status));
            });


            Trades = new ObservableCollection <TradeViewModel>();

            MakeTrade = new Command(async() =>
            {
                var asset        = TradeServiceReferential.Assets.Random();
                var counterparty = TradeServiceReferential.Counterparties.Random();

                var rand = new Random();

                var request = new TradeCreationRequest()
                {
                    Counterparty = counterparty,
                    Asset        = asset.Name,
                    Price        = asset.Price,
                    Volume       = rand.Next(1, 50),
                    Way          = TradeWay.Buy
                };

                var tradeEvent = await _tradeService.CreateTrade(request);

                var trade = await _tradeService.GetTradeById(tradeEvent.TradeId);

                Application.Current.Dispatcher.Invoke(() => Trades.Add(new TradeViewModel(trade)));
            });

            Application.Current.Dispatcher.Invoke(async() =>
            {
                var trades = await _tradeService.GetAllTrades();

                foreach (var trade in trades)
                {
                    var vm = new TradeViewModel(trade);
                    Trades.Add(vm);
                }
            });
        }