コード例 #1
0
        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();
        }
コード例 #2
0
        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();
        }
コード例 #3
0
        public void Issue42()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            var param = new NewStopLimitOrderRequestDTO
                            {
                                OrderId = 0,
                                MarketId = 99498,
                                Currency = null,
                                AutoRollover = false,
                                Direction = "buy",
                                Quantity = 10m,
                                BidPrice = 12094m,
                                OfferPrice = 12098m,
                                AuditId = "20110629-G2PREPROD3-0102794",
                                TradingAccountId = 400002249,
                                IfDone = null,
                                OcoOrder = null,
                                Applicability = null,
                                ExpiryDateTimeUTC = null,
                                Guaranteed = false,
                                TriggerPrice = 0m
                            };
            var response = rpcClient.TradesAndOrders.Order(param);


            rpcClient.LogOut();
        }
コード例 #4
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");
        }
コード例 #5
0
ファイル: Repro164.cs プロジェクト: bitpusher/SimpleCiapiTest
        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();
            }
        }
コード例 #6
0
        public void RecordNewDataForCIAPI()
        {
            var rpcClient = new Client(new Uri("https://ciapi.cityindex.com/tradingapi"), new Uri("https://push.cityindex.com"), "foobardotnet");

            // start recording requests
            var stream = new MemoryStream();
            var streamRecorder = new StreamRecorder(rpcClient, stream);
            streamRecorder.Start();

            rpcClient.LogIn("secret", "secret");

            var accountInfo = rpcClient.AccountInformation.GetClientAndTradingAccount();
            rpcClient.SpreadMarkets.ListSpreadMarkets("", "", accountInfo.ClientAccountId, 100, false);
            rpcClient.News.ListNewsHeadlinesWithSource("dj", "UK", 10);
            rpcClient.Market.GetMarketInformation(MarketId.ToString());
            rpcClient.PriceHistory.GetPriceBars(MarketId.ToString(), "MINUTE", 1, "20");
            rpcClient.TradesAndOrders.ListOpenPositions(accountInfo.SpreadBettingAccount.TradingAccountId);

            rpcClient.LogOut();

            streamRecorder.Stop();
            stream.Position = 0;

            using (var fileStream = File.Create("recorded_requests.txt"))
            {
                stream.WriteTo(fileStream);
            }
        }
コード例 #7
0
ファイル: AppKeyFixture.cs プロジェクト: Domer79/CIAPI.CS
        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();
        }
コード例 #8
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();
        }
コード例 #9
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();
        }
コード例 #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();
        }
コード例 #11
0
        public void CanListOpenPositions()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            AccountInformationResponseDTO accounts = rpcClient.AccountInformation.GetClientAndTradingAccount();
            rpcClient.TradesAndOrders.ListOpenPositions(accounts.TradingAccounts[0].TradingAccountId);
     

            rpcClient.LogOut();
        }
コード例 #12
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();
        }
コード例 #13
0
        public void Issue35()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn("xx189949", "password");

            var accountInfo = rpcClient.AccountInformation.GetClientAndTradingAccount();
            var resp = rpcClient.TradesAndOrders.ListTradeHistory(accountInfo.ClientAccountId, 20);


            rpcClient.LogOut();
        }
コード例 #14
0
        public void CanGetLookup()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            const string lookupEntityName = "OrderStatusReason";
            var orderStatus = rpcClient.Messaging.GetSystemLookup(lookupEntityName, 69);

            Assert.IsTrue(orderStatus.ApiLookupDTOList.Length > 0, "no lookup values returned for " + lookupEntityName);

            rpcClient.LogOut();
        }
コード例 #15
0
        public void Json_Ho_01()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);



            GetPriceBarResponseDTO bars = rpcClient.PriceHistory.GetPriceBars("71442", "MINUTE", 1, "15");
            Assert.IsNotNull(bars);

            rpcClient.LogOut();
        }
コード例 #16
0
ファイル: MarketFixture.cs プロジェクト: psrodriguez/CIAPI.CS
        public void CanGetMarketInformation()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            for (int i = 0; i < 10; i++)
            {
                var response = rpcClient.Market.GetMarketInformation("71442");
                Assert.IsTrue(response.MarketInformation.MarketId == 71442);
            }

            rpcClient.LogOut();
        }
コード例 #17
0
        public void CanResolveMagicNumber()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            var resolver = new MagicNumberResolver(rpcClient);
            const string lookupEntityName = MagicNumberKeys.ApiOrderResponseDTO_Status;

            string orderStatusReason = resolver.ResolveMagicNumber(lookupEntityName, 1);

            Assert.IsNotNullOrEmpty(orderStatusReason, "could not resolve magic string");

            rpcClient.LogOut();
        }
コード例 #18
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();
        }
コード例 #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();
        }
コード例 #20
0
        public void TestSubscribeMultiplePrices()
        {
            const string userName = "******";
            const string password = "******";

            var client = new Client(RPC_URI);
            client.LogIn(userName, password);

            var streamingClient = StreamingClientFactory.CreateStreamingClient(
                STREAMING_URI, userName, client.Session);

            streamingClient.Connect();

            var sync = new object();
            var listeners = new List<IStreamingListener<PriceDTO>>();
            try
            {
                var i = 0;
                var options = new ParallelOptions { MaxDegreeOfParallelism = 1 };
                Parallel.ForEach(Const.MarketIds, options,
                    marketId =>
                    {
                        lock (sync)
                        {
                            var listener = streamingClient.BuildPricesListener(new[] { marketId });
                            listeners.Add(listener);
                            listener.MessageReceived += listener_MessageReceived;
                            listener.Start();
                        }
                        Debug.WriteLine("item: {0}", i++);
                    });
                Debug.WriteLine("\r\nAll listeners created ok\r\n");
            }
            finally
            {
                var i = 0;
                foreach (var listener in listeners)
                {
                    listener.Stop();
                    Debug.WriteLine("unsubscribed item: {0}", i++);
                }
                streamingClient.Disconnect();
                client.LogOut();
            }
        }
コード例 #21
0
ファイル: Repro230.cs プロジェクト: fandrei/SimpleCiapiTest
        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);
                }
            }
        }
コード例 #22
0
        public void CanResolveDTO()
        {

            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);
            

            // this would be the value you get back from the API
            GetOpenPositionResponseDTO source = new GetOpenPositionResponseDTO
            {
                OpenPosition = new ApiOpenPositionDTO { Status = 1 }
            };

            rpcClient.MagicNumberResolver.ResolveMagicNumbers(source);

            Assert.AreEqual("Pending", source.OpenPosition.Status_Resolved, "status reason not resolved");

            rpcClient.LogOut();
        }
コード例 #23
0
        public void LogOutShouldInvalidateSession()
        {
            var rpcClient = new Client(Settings.RpcUri);
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);

            var headlines = rpcClient.News.ListNewsHeadlines("UK", 3);
            Assert.That(headlines.Headlines.Length, Is.GreaterThan(0), "you should have a set of headlines");

            rpcClient.LogOut();

            try
            {
                rpcClient.News.ListNewsHeadlines("AUS", 4);
                Assert.Fail("the previous line should have thrown an 'Session is null. Have you created a session? (logged in)' exception");
            }
            catch (ApiException e)
            {
                Assert.That(e.Message, Is.StringContaining("Session is null. Have you created a session? (logged on)"), "The client should have rejected the request");
            }
        }
コード例 #24
0
        public void HowToUseRecorderWithStream()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, AppKey);

            // start recording requests
            var stream = new MemoryStream();
            var streamRecorder = new StreamRecorder(rpcClient, stream);
            // open an array on the stream
            streamRecorder.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();

            // close the array in the stream
            streamRecorder.Stop();
            stream.Position = 0;

            var output = Encoding.UTF8.GetString(stream.ToArray());

            List<RequestInfoBase> requests = rpcClient.Serializer.DeserializeObject<List<RequestInfoBase>>(output);
            Assert.IsTrue(output.Contains("\"Target\": \"https://ciapi.cityindex.com/tradingapi/session\""));
        }
コード例 #25
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();
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: MarcRichomme/CIAPI.CS
        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;
            }


        }
コード例 #27
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);
            }
        }
コード例 #28
0
        public void DoWork()
        {
            var rpcClient = new Client(Settings.RpcUri, Settings.StreamingUri, "bogus_app_key");

            var recorder = new Recorder(rpcClient);
            recorder.Start();
            
            rpcClient.LogIn(Settings.RpcUserName, Settings.RpcPassword);


            var accounts = rpcClient.AccountInformation.GetClientAndTradingAccount();

            var response = rpcClient.CFDMarkets.ListCfdMarkets("USD", null, accounts.ClientAccountId, 500, false);

            var dto = new ListMarketInformationRequestDTO();
            dto.MarketIds = response.Markets.Select(m => m.MarketId).ToArray();
            var marketInformation = rpcClient.Market.ListMarketInformation(dto);
             rpcClient.LogOut();
            
            
            recorder.Stop();

            var json = rpcClient.Serializer.SerializeObject(recorder.GetRequests());
        }
コード例 #29
0
ファイル: MetricsFixture.cs プロジェクト: Domer79/CIAPI.CS
        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));
            }
        }
コード例 #30
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();
        }
コード例 #31
0
ファイル: Data.cs プロジェクト: fandrei/CityIndexNewsWidget
        void RefreshNewsSyncThreadEntry(Action onSuccess, Action<Exception> onError)
        {
            try
            {
                var client = new Client(RPC_URI);
                client.LogIn(USERNAME, PASSWORD);
                var resp = client.ListNewsHeadlines(ApplicationSettings.Instance.CategoryCode,
                    ApplicationSettings.Instance.MaxCount);
                News = resp.Headlines;
                client.LogOut();

                onSuccess();

            }
            catch (Exception exc)
            {
                onError(exc);
            }
        }
コード例 #32
0
        public void CanLogout()
        {
            Console.WriteLine("CanLogout");
            var server = new CassiniDevServer();
            server.StartServer(Environment.CurrentDirectory);

            var ctx = new Client(new Uri(server.NormalizeUrl("/")), new Uri(server.NormalizeUrl("/")), "foo")
                          {
                              UserName = "******",
                              Session = "123"
                          };


            server.Server.ProcessRequest += (i, e) =>
            {
                e.Continue = false;
                e.Response = LoggedOut;

            };


            bool response;
            try
            {
                response = ctx.LogOut();
            }
            finally
            {
                server.Dispose();
            }

            Assert.IsTrue(response);

        }
コード例 #33
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();

        }
コード例 #34
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();
        }