Exemplo n.º 1
0
        public void CanSendMetrics()
        {

            // set up a listener
            var log = new StringBuilder();
            var writer = new StringWriter(log);
            var listener = new TextWriterTraceListener(writer);
            Trace.Listeners.Add(listener);

            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, "my-test-appkey");
            var metricsRecorder = new MetricsRecorder(rpcClient, new Uri("http://metrics.labs.cityindex.com/LogEvent.ashx"));
            metricsRecorder.Start();

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);

            foreach (var item in headlines.Headlines)
            {
                rpcClient.News.GetNewsDetail("dj", item.StoryId.ToString());
            }

            new AutoResetEvent(false).WaitOne(10000);

            rpcClient.LogOut();

            metricsRecorder.Stop();
            rpcClient.Dispose();

            Trace.Listeners.Remove(listener);

            var logText = log.ToString();

            Assert.IsTrue(logText.Contains("Latency message complete"), "did not find evidence of metrics being posted");
        }
        public void CanMockCiapiServerConversation()
        {
            Uri uri = new Uri(NormalizeUrl("/"));
            var rpcClient = new Client(uri, uri, "foobardotnet");

            rpcClient.LogIn("Foo", "Bar");

            Assert.AreEqual("5f28983b-0e0a-4a57-92af-0d07c6fdbc38", rpcClient.Session);

            // get some headlines
            var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);
            Assert.AreEqual(100, headlines.Headlines.Length);

            // get a story id from one of the headlines
            var storyId = headlines.Headlines[0].StoryId;
            Assert.AreEqual(1416482, storyId);

            var storyDetail = rpcClient.News.GetNewsDetail("dj", storyId.ToString());

            Assert.IsTrue(storyDetail.NewsDetail.Story.Contains("By Anita Greil "));

            rpcClient.LogOut();

            rpcClient.Dispose();
        }
Exemplo n.º 3
0
        private static void DoPolling()
        {
            var client = new Client(Const.RPC_URI, Const.STREAMING_URI, "Test.{B4E415A7-C453-4867-BDD1-C77ED345777B}");
            try
            {
                client.AppKey = "Test";
                client.StartMetrics();

                client.LogIn(Const.USERNAME, Const.PASSWORD);

                for (int i = 0; i < 10; i++)
                {
                    var accountInfo = client.AccountInformation.GetClientAndTradingAccount();
                    client.TradesAndOrders.ListOpenPositions(accountInfo.CFDAccount.TradingAccountId);
                    Thread.Sleep(1000);
                }

                client.LogOut();
            }
            catch (Exception exc)
            {
                Trace.WriteLine(exc);
            }
            finally
            {
                client.Dispose();
            }
        }
        public void CanChangePassword()
        {
            const string NEWPASSWORD = "******";
            var rpcClient = new Client(Settings.RpcUri,Settings.StreamingUri, AppKey);
            
            //Login with existing credentials
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            //And change password
            var changePasswordResponse = rpcClient.Authentication.ChangePassword(new ApiChangePasswordRequestDTO()
                                                                                         {
                                                                                             UserName = Settings.RpcUserName,
                                                                                             Password = Settings.RpcPassword,
                                                                                             NewPassword = NEWPASSWORD
                                                                                         });

            Assert.IsTrue(changePasswordResponse.IsPasswordChanged);
            rpcClient.LogOut();

            //Make sure that login existing password fails 
            Assert.Throws<ReliableHttpException>(() => rpcClient.LogIn(Settings.RpcUserName, Settings.RpcUserName));

            //Login with changed password and change back
            rpcClient.LogIn(Settings.RpcUserName, NEWPASSWORD);
            changePasswordResponse = rpcClient.Authentication.ChangePassword(new ApiChangePasswordRequestDTO()
                                                                                         {
                                                                                             UserName = Settings.RpcUserName,
                                                                                             Password = NEWPASSWORD,
                                                                                             NewPassword = Settings.RpcPassword
                                                                                         });

            Assert.IsTrue(changePasswordResponse.IsPasswordChanged);
            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 5
0
        public void AppKeyIsAppendedToLogonRequest()
        {
            // look at the log to verify - need to expose interals and provide a means to examine the cache to verify programmatically

            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, "my-test-appkey");
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 6
0
        public void InvalidLoginShouldThrow()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);
            rpcClient.LogIn(Settings.RpcUserName, "foo");

            Assert.That(rpcClient.Session, Is.Not.Empty);

            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 7
0
        public void LoginShouldCreateSession()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient.Session, Is.Not.Empty);

            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 8
0
        public void CheckNetLatency()
        {
            Console.WriteLine("Checking .net latency");

            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo");

            DateTimeOffset requestRecieved = DateTimeOffset.MinValue;
            RequestCompletedEventArgs requestInfo = null;
            ctx.RequestCompleted += (i, e) =>
                                        {
                                            requestInfo = e;
                                        };
            server.Server.ProcessRequest += (i, e) =>
                                                {
                                                    e.Continue = false;
                                                    e.Response = LoggedIn;
                                                    e.ResponseStatus = 200;
                                                    requestRecieved = DateTimeOffset.UtcNow;

                                                };


            try
            {
                ctx.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            }
            finally
            {
                server.Dispose();
            }

            Console.WriteLine("elapsed   {0}", requestInfo.Info.Watch.ElapsedMilliseconds);

            // #TODO: not sure i like the complete removal of temporal data

            //Console.WriteLine("issued   {0}", requestInfo.Info.Issued.Ticks);
            //Console.WriteLine("recieved {0}", requestRecieved.Ticks);
            //Console.WriteLine("competed {0}", requestInfo.Info.Completed.Ticks);

            //Console.WriteLine("issued to recieved {0}", TimeSpan.FromTicks(requestRecieved.Ticks - requestInfo.Info.Issued.Ticks));
            //Console.WriteLine("recieved to completed {0}", TimeSpan.FromTicks(requestInfo.Info.Completed.Ticks - requestRecieved.Ticks));
            //Console.WriteLine("issued to completed {0}", TimeSpan.FromTicks(requestInfo.Info.Completed.Ticks - requestInfo.Info.Issued.Ticks));


            

            Assert.IsNotNullOrEmpty(ctx.Session);



            ctx.Dispose();
        }
Exemplo n.º 9
0
        public void InvalidLoginShouldThrow()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient.LogIn(Settings.RpcUserName, "foo");

            Assert.That(rpcClient.Session, Is.Not.Empty);

            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 10
0
        public void LoginShouldCreateSession()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient.Session, Is.Not.Empty);

            rpcClient.LogOut();
            rpcClient.Dispose();
        }
Exemplo n.º 11
0
        public void LoginUsingSessionShouldValidateSession()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient.Session, Is.Not.Null.Or.Empty);

            //This should work
            var rpcClientUsingSession = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, rpcClient.Session);

            Assert.That(rpcClientUsingSession.Session, Is.Not.Null.Or.Empty);

            //After the session has been destroyed, trying to login using it should fail
            rpcClient.LogOut();


            try
            {
                rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, rpcClient.Session);
                Assert.Fail("should throw");
            }
            catch (ReliableHttpException)
            {
            }

            try
            {
                rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, Guid.NewGuid().ToString());
                Assert.Fail("should throw");
            }
            catch (ReliableHttpException)
            {
            }

            //And there shouldn't be a session
            Assert.IsNullOrEmpty(rpcClientUsingSession.Session);


            // this client is already logged out. should we swallow unauthorized exceptions in the logout methods?
            // rpcClientUsingSession.LogOut();
            rpcClientUsingSession.Dispose();
            rpcClient.Dispose();
        }
Exemplo n.º 12
0
        private static void DoPolling()
        {
            var client = new Client(Const.RPC_URI, Const.STREAMING_URI, "Test.{B4E415A7-C453-4867-BDD1-C77ED345777B}");
            try
            {
                client.LogIn(Const.USERNAME, Const.PASSWORD);

                using (var streamingClient = client.CreateStreamingClient())
                {
                    var topics = new[] { 99498, 99500 };
                    using (var pricesListener = streamingClient.BuildPricesListener(topics))
                    {
                        var finished = new ManualResetEvent(false);

                        pricesListener.MessageReceived +=
                            (s, e) =>
                            {
                                finished.Set();
                                Console.WriteLine("{0} -> {1}", e.Data.MarketId, e.Data.Price);
                            };

                        finished.WaitOne(10000);

                        streamingClient.TearDownListener(pricesListener);
                    }
                }

                client.LogOut();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
            finally
            {
                try
                {
                    client.Dispose();
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc);
                }
            }
        }
Exemplo n.º 13
0
        public void CanLogin()
        {
    
            var server = new TestServer(true);
            server.Start();

            
            
            server.ProcessRequest += (s, e) =>
                                         {
                                             var dto = new ApiLogOnResponseDTO
                                                           {
                                                               AllowedAccountOperator = true,
                                                               PasswordChangeRequired = false,
                                                               Session =
                                                                   "86c6b0df-24d4-4b3f-b699-688626817599"
                                                           };
                                             string json = JsonConvert.SerializeObject(dto);
                                             e.Response = TestServer.CreateRpcResponse(json);
                                         };
            try
            {

                var ctx = new Client(new Uri("http://localhost.:" + server.Port), new Uri("http://localhost.:" + server.Port), "foo");

                ctx.LogIn(Settings.RpcUserName, Settings.RpcPassword);
                
                Assert.IsNotNullOrEmpty(ctx.Session);
                ctx.Dispose();

            }
            finally
            {
                server.Stop();
            }



            

        }
Exemplo n.º 14
0
        public void ShouldWorkWithNewGetMarketInformationResponseDTO()
        {
            var factory = new TestRequestFactory();

            var rpcClient = new Client(new Uri("https://test.com/tradingapi"), new Uri("https://test.com"), "test", new Serializer(), factory);

            var requests = new List<RequestInfoBase>
                               {
                                   new RequestInfoBase
                                       {
                                           Index = 0,
                                           ResponseText =
                                               "{\"AllowedAccountOperator\":false,\"PasswordChangeRequired\":false,\"Session\":\"99be8650-d9a3-47cc-a506-044e87db457d\"}"
                                       },
                                   new RequestInfoBase
                                       {
                                           Index = 1,
                                           ResponseText =
                                               "{\"MarketInformation\":{\"MarketId\":400160010,\"Name\":\"UK 100 CFD\",\"MarginFactor\":1.00000000,\"MinMarginFactor\":null,\"MaxMarginFactor\":null,\"MarginFactorUnits\":26,\"MinDistance\":0.00,\"WebMinSize\":3.00000000,\"MaxSize\":2000.00000000,\"Market24H\":true,\"PriceDecimalPlaces\":0,\"DefaultQuoteLength\":180,\"TradeOnWeb\":true,\"LimitUp\":false,\"LimitDown\":false,\"LongPositionOnly\":false,\"CloseOnly\":false,\"MarketEod\":[],\"PriceTolerance\":2.0,\"ConvertPriceToPipsMultiplier\":10000,\"MarketSettingsTypeId\":2,\"MarketSettingsType\":\"CFD\",\"MobileShortName\":\"UK 100\",\"CentralClearingType\":\"No\",\"CentralClearingTypeDescription\":\"None\",\"MarketCurrencyId\":6,\"PhoneMinSize\":3.00000000,\"DailyFinancingAppliedAtUtc\":\"\\/Date(1338238800000)\\/\",\"NextMarketEodTimeUtc\":\"\\/Date(1338238800000)\\/\",\"TradingStartTimeUtc\":null,\"TradingEndTimeUtc\":null,\"MarketPricingTimes\":[{\"DayOfWeek\":1,\"StartTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338249600000)\\/\",\"OffsetMinutes\":60},\"EndTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338321600000)\\/\",\"OffsetMinutes\":60}},{\"DayOfWeek\":2,\"StartTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338249600000)\\/\",\"OffsetMinutes\":60},\"EndTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338321600000)\\/\",\"OffsetMinutes\":60}},{\"DayOfWeek\":3,\"StartTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338249600000)\\/\",\"OffsetMinutes\":60},\"EndTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338321600000)\\/\",\"OffsetMinutes\":60}},{\"DayOfWeek\":4,\"StartTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338249600000)\\/\",\"OffsetMinutes\":60},\"EndTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338321600000)\\/\",\"OffsetMinutes\":60}},{\"DayOfWeek\":5,\"StartTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338249600000)\\/\",\"OffsetMinutes\":60},\"EndTimeUtc\":{\"UtcDateTime\":\"\\/Date(1338321600000)\\/\",\"OffsetMinutes\":60}}],\"MarketBreakTimes\":[],\"MarketSpreads\":[{\"SpreadTimeUtc\":\"\\/Date(1338321600000)\\/\",\"Spread\":6.000000000,\"SpreadUnits\":27},{\"SpreadTimeUtc\":\"\\/Date(1338271440000)\\/\",\"Spread\":4.000000000,\"SpreadUnits\":27},{\"SpreadTimeUtc\":\"\\/Date(1338274200000)\\/\",\"Spread\":6.000000000,\"SpreadUnits\":27},{\"SpreadTimeUtc\":\"\\/Date(1338274800000)\\/\",\"Spread\":2.000000000,\"SpreadUnits\":27}],\"GuaranteedOrderPremium\":3.00,\"GuaranteedOrderPremiumUnits\":1,\"GuaranteedOrderMinDistance\":30.00,\"GuaranteedOrderMinDistanceUnits\":27,\"PriceToleranceUnits\":1.00000,\"MarketTimeZoneOffsetMinutes\":60,\"BetPer\":1.00000,\"MarketUnderlyingTypeId\":2,\"MarketUnderlyingType\":\"Index\",\"ExpiryUtc\":null}}"
                                       }
                               };
            var finder = new TestWebRequestFinder { Reference = requests };
            var requestCounter = 0;
            factory.PrepareResponse = testRequest =>
            {
                finder.PopulateRequest(testRequest, requests[requestCounter]);
                requestCounter++;
            };

            rpcClient.LogIn("username", "password");

            var marketInfo = rpcClient.Market.GetMarketInformation("400494178");

            Assert.IsNotNullOrEmpty(marketInfo.MarketInformation.Name, "Market should have a name");
            Assert.That(marketInfo.MarketInformation.MarketPricingTimes[1].EndTimeUtc.UtcDateTime,
                        Is.EqualTo(DateTime.Parse("2012-05-29 20:00:00.000")));


            rpcClient.Dispose();
        }
Exemplo n.º 15
0
        public void CanSimultaneousSessionsExist()
        {
            var rpcClient1 = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);
            rpcClient1.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient1.Session, Is.Not.Empty);

            var rpcClient2 = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);
            rpcClient2.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient2.Session, Is.Not.Empty);


            var result1 = rpcClient1.AccountInformation.GetClientAndTradingAccount();
            var result2 = rpcClient2.AccountInformation.GetClientAndTradingAccount();

            rpcClient1.LogOut();
            rpcClient1.Dispose();

            rpcClient2.LogOut();
            rpcClient2.Dispose();
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            try
            {
                LogManager.CreateInnerLogger = (logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat)
              => new SimpleDebugAppender(logName, logLevel, showLevel, showDateTime, showLogName, dateTimeFormat);

                var client = new Client(new Uri("https://ciapi.cityindex.com/tradingapi"));
                var loginResponse = client.LogIn("DM715257", "password");
                if (loginResponse.PasswordChangeRequired)
                {
                    throw new Exception("must change password");
                }
                var streamingClient = StreamingClientFactory.CreateStreamingClient(new Uri("https://push.cityindex.com"), client.UserName,
                                                                                   client.Session);
                var newsStream = streamingClient.BuildNewsHeadlinesListener("UK");
                newsStream.MessageReceived += new EventHandler<StreamingClient.MessageEventArgs<CIAPI.DTO.NewsDTO>>(newsStream_MessageReceived);

                Console.WriteLine("listening for 30 seconds");
                new AutoResetEvent(false).WaitOne(30000);
                
                Console.WriteLine("press enter to exit");
                Console.ReadLine();
                streamingClient.TearDownListener(newsStream);
                streamingClient.Dispose();
                client.LogOut();
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine("press enter to exit");
                Console.ReadLine();
                throw;
            }


        }
Exemplo n.º 17
0
        public void CanSimultaneousSessionsExist()
        {
            var rpcClient1 = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient1.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient1.Session, Is.Not.Empty);

            var rpcClient2 = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient2.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient2.Session, Is.Not.Empty);


            var result1 = rpcClient1.AccountInformation.GetClientAndTradingAccount();
            var result2 = rpcClient2.AccountInformation.GetClientAndTradingAccount();

            rpcClient1.LogOut();
            rpcClient1.Dispose();

            rpcClient2.LogOut();
            rpcClient2.Dispose();
        }
Exemplo n.º 18
0
        public void ReplaySerializedRequests()
        {
            var serialized = File.ReadAllText("RPC\\RecordedRequests01.txt");


            TestRequestFactory factory = new TestRequestFactory();

            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey, new Serializer(), factory);


            var requests = rpcClient.Serializer.DeserializeObject<List<RequestInfoBase>>(serialized);
            var finder = new TestWebRequestFinder { Reference = requests };

            // setup a callback on the test request factory so that we can populate the response using the recorded data

            factory.PrepareResponse = testRequest =>
            {

                // look for a matching request in our recording using the uri and request body
                var match = finder.FindMatchExact(testRequest);

                if (match == null)
                {
                    throw new Exception("no matching request found");
                }


                finder.PopulateRequest(testRequest, match);

            };

            // now that our request stack is set up, we can make the same calls with repeatable results


            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            Assert.AreEqual("5f28983b-0e0a-4a57-92af-0d07c6fdbc38", rpcClient.Session);

            // get some headlines
            var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);
            Assert.AreEqual(100, headlines.Headlines.Length);

            // get a story id from one of the headlines
            var storyId = headlines.Headlines[0].StoryId;
            Assert.AreEqual(1416482, storyId);

            var storyDetail = rpcClient.News.GetNewsDetail("dj", storyId.ToString());

            Assert.IsTrue(storyDetail.NewsDetail.Story.Contains("By Anita Greil "));

            rpcClient.LogOut();


            rpcClient.Dispose();
        }
Exemplo n.º 19
0
        public void LoginUsingSessionShouldValidateSession()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            Assert.That(rpcClient.Session, Is.Not.Null.Or.Empty);

            //This should work
            var rpcClientUsingSession = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, rpcClient.Session);
                
            Assert.That(rpcClientUsingSession.Session, Is.Not.Null.Or.Empty);

            //After the session has been destroyed, trying to login using it should fail
            rpcClient.LogOut();
     

            try
            {
                rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, rpcClient.Session);
                Assert.Fail("should throw");
            }
            catch (ReliableHttpException)
            {
                
            }

            try
            {
                rpcClientUsingSession.LogInUsingSession(Settings.RpcUserName, Guid.NewGuid().ToString());
                Assert.Fail("should throw");
            }
            catch (ReliableHttpException)
            {

            }
 
            //And there shouldn't be a session
            Assert.IsNullOrEmpty(rpcClientUsingSession.Session);


            // this client is already logged out. should we swallow unauthorized exceptions in the logout methods?
            // rpcClientUsingSession.LogOut();
            rpcClientUsingSession.Dispose();
            rpcClient.Dispose();
        }
Exemplo n.º 20
0
        public void MetricsAreSentWithSelectedSessionIdentifier()
        {
            var startTime = DateTime.UtcNow;
            var metricsSession = "MetricsAreSentWithSelectedSessionIdentifier_" + Guid.NewGuid();

            // set up a listener
            var log = new StringBuilder();
            var writer = new StringWriter(log);
            var listener = new TextWriterTraceListener(writer);
            Trace.Listeners.Add(listener);

            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, "my-test-appkey");

            var metricsRecorder = new MetricsRecorder(rpcClient, new Uri(MetricsUrl + "LogEvent.ashx"), metricsSession, Settings.AppMetrics_AccessKey);
            metricsRecorder.Start();

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            rpcClient.LogOut();

            metricsRecorder.Stop();
            rpcClient.Dispose();

            Trace.Listeners.Remove(listener);

            using (var client = new WebClient())
            {
                client.Credentials = new NetworkCredential(Settings.AppMetrics_UserName, Settings.AppMetrics_Password);
                client.QueryString["AppKey"] = "my-test-appkey";
                client.QueryString["StartTime"] = startTime.ToString("u");

                var response = client.DownloadString(MetricsUrl + "GetSessions.ashx");

                Assert.IsTrue(response.Contains(metricsSession));
            }
        }
Exemplo n.º 21
0
        public void CanUseFiddlerSessionsToServeRpcCalls()
        {
            var parser = new Parser();

            // parse saved sessions into collection of session objects
            string path = @"..\..\..\TestingInfrastructure\Fiddler\5_Full.txt";
            var sessions = parser.ParseFile(path);


            var engine = new FiddlerRequestEngine(sessions);


            var server = new TestServer(true);

            string recordedUrl = "https://ciapi.cityindex.com/tradingapi";

         


            server.ProcessRequest += (s, e) =>
                                         {
                                             string requestMethod = e.Request.Method;
                                             string requestUrl = recordedUrl + e.Request.Url;

                                             var session = engine.FindSession(requestMethod, requestUrl);

                                             if (session == null)
                                             {
                                                 

                                                 e.Response = new ServerBase.ResponseInfo
                                                 {
                                                     Status = "404 Not Found"
                                                 };
                                             }
                                             else
                                             {
                                                e.Response = new ServerBase.ResponseInfo
                                                              {
                                                                  Headers = new NameValueCollection(session.Response.Headers),
                                                                  Status = session.Response.StatusCode + " " + session.Response.Status,
                                                                  Body = session.Response.Body
                                                              };    
                                                 }
                                            
                                         };


            server.Start();




            var rpcClient = new Client(new Uri("http://localhost.:" + server.Port), new Uri("http://localhost.:" + server.Port), AppKey);

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            AccountInformationResponseDTO accounts = rpcClient.AccountInformation.GetClientAndTradingAccount();
            rpcClient.TradesAndOrders.ListOpenPositions(accounts.TradingAccounts[0].TradingAccountId);
            rpcClient.LogOut();
            rpcClient.Dispose();

            server.Stop();

        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            try
            {
                var adapter = new MyLoggerFactoryAdapter(null) { OnMessage = AddLogMessage };
                LogManager.Adapter = adapter;

                _client = new Client(RPC_URI);
                _client.LogIn(USERNAME, PASSWORD);

                _streamingClient = StreamingClientFactory.CreateStreamingClient(STREAMING_URI, USERNAME, _client.Session);
                _streamingClient.Connect();

                Console.WriteLine("Connected");

                var accountInfo = _client.AccountInformation.GetClientAndTradingAccount();
                var markets = _client.CFDMarkets.ListCfdMarkets("", "", accountInfo.ClientAccountId, -1).Markets;

                var marketIds = markets.Select(market => market.MarketId).ToArray();

                var listener = _streamingClient.BuildPricesListener(marketIds);
                listener.MessageReceived += OnMessageReceived;
                listener.Start();

                Console.ReadKey();

                _streamingClient.Disconnect();

                _client.LogOut();
                _client.Dispose();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
                Trace.WriteLine(exc);
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            try
            {
                var curProcess = Process.GetCurrentProcess();
                var secondsOnStart = curProcess.TotalProcessorTime.TotalSeconds;
                var totalWatch = Stopwatch.StartNew();

                for (int i = 0; i < 20; i++)
                {
                    var client = new Client(Const.RPC_URI, Const.STREAMING_URI, "");
                    var recorder = new Recorder(client);
                    recorder.Start();

                    var loginWatch = Stopwatch.StartNew();
                    client.LogIn(Const.USERNAME, Const.PASSWORD);
                    loginWatch.Stop();

                    var accountInfoWatch = Stopwatch.StartNew();
                    var accountInfo = client.AccountInformation.GetClientAndTradingAccount();
                    accountInfoWatch.Stop();

                    var listSpreadMarketsWatch = Stopwatch.StartNew();
                    var resp = client.SpreadMarkets.ListSpreadMarkets("", "",
                        accountInfo.ClientAccountId, 100, false);
                    listSpreadMarketsWatch.Stop();

                    var logoutWatch = Stopwatch.StartNew();
                    client.LogOut();
                    logoutWatch.Stop();

                    var purgeHandle = client.ShutDown();
                    if (!purgeHandle.WaitOne(60000))
                        throw new ApplicationException();

                    var requests = recorder.GetRequests();
                    if (requests.Count != 4)
                        throw new ApplicationException();

                    AddResult(loginWatch, requests[0], "Login");
                    AddResult(accountInfoWatch, requests[1], "GetClientAndTradingAccount");
                    AddResult(listSpreadMarketsWatch, requests[2], "ListSpreadMarkets");
                    AddResult(logoutWatch, requests[3], "Logout");

                    recorder.Stop();
                    recorder.Dispose();
                    client.Dispose();
                }

                totalWatch.Stop();
                var secondsOnEnd = curProcess.TotalProcessorTime.TotalSeconds;
                Console.WriteLine("CPU time used, seconds: {0} total time: {1}", secondsOnEnd - secondsOnStart, totalWatch.Elapsed.TotalSeconds);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }

            Debugger.Break();
        }
Exemplo n.º 24
0
        public void CanStream()
        {
            var server = new TestServer(true);
            server.Start();



            server.ProcessRequest += (s, e) =>
                                         {
                                             const string defaultPricesSessionid = "S8f295c055c413e4bT4448618";

                                             switch (e.Request.Route)
                {
                    // Streaming requests




                    case "/lightstreamer/create_session.txt":
                        // build up a session for adapter set

                        string response = string.Format(@"OK
SessionId:{0}
ControlAddress:localhost.
KeepaliveMillis:30000
MaxBandwidth:0.0
RequestLimit:50000
ServerName:Lightstreamer HTTP Server

PROBE
LOOP
", defaultPricesSessionid);


                        e.Response = TestServer.CreateLightStreamerResponse(response);
                        break;


                    case "/lightstreamer/control.txt":
                        // this is where we associate topics (tables) to a session

                        e.Response = TestServer.CreateLightStreamerResponse(@"OK
");
                        
                        break;
                    case "/lightstreamer/bind_session.txt":
                        // this is where we return data. we can't use long polling with cassinidev 


                        e.Response = TestServer.CreateLightStreamerResponse(string.Format(@"OK
SessionId:{0}
ControlAddress:localhost.
KeepaliveMillis:30000
MaxBandwidth:0.0
RequestLimit:50000

PROBE
1,5|#|#|#|#|#|#|#|#|#|#|#
1,1|sbPreProdFXAPP475974420|1.61793|-0.00114|1|1.62006|1.61737|400494226|1.61799|1.61796|0|\u005C/Date(1349422105265)\u005C/
1,4|sbPreProdFXAPP1416588099|0.93575|-0.00275|0|0.93892|0.93508|400494241|0.93603|0.93589|0|\u005C/Date(1349353115700)\u005C/
1,6|sbPreProdFXAPP475774416|1.21135|0.00019|1|1.21191|1.21109|400494215|1.21160|1.21147|0|\u005C/Date(1349422103923)\u005C/
1,7|sbPreProdFXAPP475974395|101.908|-0.245|1|102.279|101.863|400494220|101.929|101.918|0|\u005C/Date(1349422105171)\u005C/
1,8|sbPreProdFXAPP475774545|1.02494|0.00097|1|1.02746|1.02385|400494179|1.02513|1.02503|0|\u005C/Date(1349422104906)\u005C/
1,3|sbPreProdFXAPP475824759|1.610|-0.001|1|1.620|1.617|400494246|1.625|1.618|0|\u005C/Date(1349422105265)\u005C/
1,2|sbPreProdFXAPP475824757|1.61791|-0.00114|1|1.62006|1.61737|400494234|1.61801|1.61796|0|\u005C/Date(1349422105265)\u005C/
LOOP

", defaultPricesSessionid));
                        

                        break;

                    default:
                        throw new Exception("unexpected request:" + e.Request.Route);

                }
                                         };



            try
            {

                var ctx = new Client(new Uri("http://localhost.:" + server.Port), new Uri("http://localhost.:" + server.Port), "foo");
                ctx.Session = "session";
                ctx.UserName = "******";

                var streaming = ctx.CreateStreamingClient();
                var listener = streaming.BuildDefaultPricesListener(9);

                bool streamingMessageRecieved = false;

                listener.MessageReceived += (a, r) =>
                {
                    Console.WriteLine(r.Data.ToStringWithValues());
                    streamingMessageRecieved = true;

                };
                Thread.Sleep(3000);

                streaming.TearDownListener(listener);
                streaming.Dispose();
                ctx.Dispose();

                Assert.IsTrue(streamingMessageRecieved, "no streaming message recieved");



            }
            finally
            {
                server.Stop();
            }
        }
Exemplo n.º 25
0
        public void ReplaySerializedRequestsByIndex()
        {
            var serialized = File.ReadAllText("RPC\\RecordedRequests02.txt");


            TestRequestFactory factory = new TestRequestFactory();

            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey, new Serializer(), factory);
            // adds an 'x-request-index' header to each request
            rpcClient.IncludeIndexInHeaders = true;

            var requests = rpcClient.Serializer.DeserializeObject<List<RequestInfoBase>>(serialized);
            var finder = new TestWebRequestFinder { Reference = requests };

            // setup a callback on the test request factory so that we can populate the response using the recorded data

            factory.PrepareResponse = testRequest =>
            {

                // look for a matching request in our recording using the uri and request body
                var match = finder.FindMatchBySingleHeader(testRequest, "x-request-index");

                if (match == null)
                {
                    throw new Exception("no matching request found");
                }

                finder.PopulateRequest(testRequest, match);
            };

            // now that our request stack is set up, we can make the same calls with repeatable results


            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            Assert.AreEqual("ecbeff35-e5b7-4c15-bb2e-52232360f575", rpcClient.Session);

            // get some headlines
            var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);
            Assert.AreEqual(100, headlines.Headlines.Length);

            // get a story id from one of the headlines
            var storyId = headlines.Headlines[0].StoryId;
            Assert.AreEqual(1409880, storyId);

            var storyDetail = rpcClient.News.GetNewsDetail("dj", storyId.ToString());

            Assert.IsTrue(storyDetail.NewsDetail.Story.Contains("The latest official U.K. data release Thursday"));

            rpcClient.LogOut();


            rpcClient.Dispose();
        }
Exemplo n.º 26
0
        public void HowToUseRecorder()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            // start recording requests
            var recorder = new Recorder(rpcClient);
            recorder.Start();

            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);





            // get some headlines
            var headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);

            // get a story id from one of the headlines
            var storyId = headlines.Headlines[0].StoryId;

            // get the body of the story
 
            var storyDetail = rpcClient.News.GetNewsDetail("dj", storyId.ToString());

            Assert.IsNotNullOrEmpty(storyDetail.NewsDetail.Story, "story was empty?");


            rpcClient.LogOut();
            recorder.Stop();

            List<RequestInfoBase> requests = recorder.GetRequests();
            // let's serialize the recorded requests to simulate typical usage because you typically would use pre-canned data
            // to run unit tests agains.
            var requestsSerialized = rpcClient.Serializer.SerializeObject(requests);

            rpcClient.Dispose();





            // now we will use our recorded (and serialized) request data to run the same requests through the client 
            // without actually sending any requests over the wire.


            TestRequestFactory factory = new TestRequestFactory();

            rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey, new Serializer(), factory);
            rpcClient.IncludeIndexInHeaders = true;

            requests = rpcClient.Serializer.DeserializeObject<List<RequestInfoBase>>(requestsSerialized);
            var finder = new TestWebRequestFinder { Reference = requests };

            // setup a callback on the test request factory so that we can populate the response using the recorded data

            factory.PrepareResponse = testRequest =>
                {

                    // look for a matching request in our recording using the uri and request body
                    var match = finder.FindMatchExact(testRequest);

                    if (match == null)
                    {
                        throw new Exception("no matching request found");
                    }
                    finder.PopulateRequest(testRequest, match);
                };

            // now that our request stack is set up, we can make the same calls with repeatable results


            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            // get some headlines
            headlines = rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 100);

            // get a story id from one of the headlines
            storyId = headlines.Headlines[0].StoryId;

            storyDetail = rpcClient.News.GetNewsDetail("dj", storyId.ToString());

            Assert.IsNotNullOrEmpty(storyDetail.NewsDetail.Story, "story was empty?");


            rpcClient.LogOut();
            rpcClient.Dispose();
        }
        public void MockMultipleStreams()
        {
           
            // set up the server to mock responses so that we can utilize actual client instances for testing

            var server = new TestServer(true);

            try
            {
                server.Start();

                server.ProcessRequest += (i, e) =>
                {


                    if (e.Request.Route.StartsWith("/lightstreamer"))
                    {
                        ProcessStreamingRequest(e);
                    }
                    else
                    {
                        ProcessRpcRequest(e);
                    }

                };


                // now use the libraries as you normally would 

                var uri = new Uri("http://localhost.:" + server.Port);
                var ctx = new Client(uri, uri, "foo");

                var loginResponse = ctx.LogIn("foo", "bar");


                // only difference here is that we MUST force polling mode on the lightstreamer client
                var streamingClient = ctx.CreateStreamingClient();

                var gates = new AutoResetEvent[] { new AutoResetEvent(false), new AutoResetEvent(false) };
                bool defaultPricesListenerMessageRecieved = false;
                bool pricesListenerMessageRecieved = false;

                var defaultPricesListener = streamingClient.BuildDefaultPricesListener(9);
                defaultPricesListener.MessageReceived += (a, r) =>
                {
                    Console.WriteLine("\n***********************************\nDEFAULT PRICE\n***********************************\n");
                    defaultPricesListenerMessageRecieved = true;
                    gates[0].Set();
                };

                var pricesListener = streamingClient.BuildPricesListener(new[] { 99498, 99500 });
                pricesListener.MessageReceived += (a, r) =>
                {
                    Console.WriteLine("\n***********************************\nPRICE\n***********************************\n");
                    pricesListenerMessageRecieved = true;
                    gates[1].Set();
                };

                if(!WaitHandle.WaitAll(gates,20000))
                {
                    throw new Exception("timed out waiting for events");
                } 

                streamingClient.TearDownListener(defaultPricesListener);
                streamingClient.TearDownListener(pricesListener);
                streamingClient.Dispose();

                ctx.LogOut();
                ctx.Dispose();
 
            }
            finally
            {
                server.Stop();
            }


        }