public void Test()
        {
            var requestFactory = new TestRequestFactory();
            requestFactory.RequestTimeout = TimeSpan.FromSeconds(30);
            requestFactory.PrepareResponse = r =>
                                                 {
                                                     byte[] responseBytes = Encoding.UTF8.GetBytes("{\"Id\":1}");
                                                     r.ResponseStream.Write(responseBytes, 0, responseBytes.Length);
                                                     r.ResponseStream.Seek(0, SeekOrigin.Begin);
                                                 };
            var client = new SampleClient("http://foo.com", requestFactory);

            var gate = new AutoResetEvent(false);
            TestClass response = null;
            client.BeginGetTestClass(ar =>
                                         {

                                             response = client.EndGetTestClass(ar);
                                             gate.Set();
                                         }, null);

            if (!gate.WaitOne(40000))
            {
                throw new Exception("timed out");
            }

            Assert.AreEqual(1, response.Id);

        }
        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();
        }
 public MockClient(IJsonSerializer serializer)
     : base(serializer)
 {
     var requestFactory = new TestRequestFactory();
     Controller = new RequestController(serializer ,requestFactory);
 }
        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 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();
        }
        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();
        }