Exemple #1
0
 public void SetupCommonConfiguration()
 {
     _configuration = RestConfiguration.JsonDefault();
     _configuration.WithHeader("User-Agent", "RestFluencing Sample");
     _configuration.WithBaseUrl("https://api.github.com/");
     _configuration.WithBasicAuthorization("<username>", "<password>");
 }
Exemple #2
0
        public void Test()
        {
            // Steps for creating a new client
            //   1 - Create your client = MultipartContentApiClient
            //		Optional : override the HttpClientBase
            //   2 - Create your builder = MultipartContentApiClientBuilder
            //   3 - Create your extensions (those are helpers for ease of use - MultiPartContentApiClientBuilderExtensions and MultipartRequestExtensions)
            //   Optional : create your own request type


            var config =
                new RestConfiguration()
                .WithBaseUrl("http://localhost:8080/")
                .UseJsonResponseDeserialiser()
                .UsingMultipartApiClient();

            config.RequestDefaults.TimeoutInSeconds = 90;

            config.Post("/")

            .WithMultipart(r => r.Add(new StringContent("value"), "key"))

            .Response()
            .ReturnsStatus(HttpStatusCode.OK);
        }
        public async Task <LoginResult> Login(RestConfiguration configuration, string username, string password)
        {
            var configurationHeaders = LoginConfigurationToHeaders(configuration);

            var loginParameters = new Dictionary <string, string>
            {
                { "username", username },
                { "password", password }
            };

            var loginResponse = await _restService.SendRestGetRequest(LoginUrl, configurationHeaders, loginParameters);

            if (loginResponse.Status == RestResponseStatus.Ok)
            {
                return(new LoginResult
                {
                    ResultStatus = LoginStatus.Successful,
                    Session = ParseRestSession(loginResponse.Data, configuration)
                });
            }

            return(new LoginResult {
                ResultStatus = LoginStatus.Unknown
            });
        }
Exemple #4
0
 public void Setup()
 {
     _assertion               = new Mock <IAssertion>();
     _configuration           = RestConfigurationHelper.Default();
     _configuration.Assertion = _assertion.Object;
     _factory = _configuration.ClientFactory as TestApiFactory;
 }
        public void WhenNoClientShouldSetTheHttpApiClientBuilder()
        {
            var config = new RestConfiguration();

            config.UsingWebApiClient();

            Assert.IsInstanceOfType(config.ClientFactory, typeof(HttpApiClientBuilder));
        }
        public void SetupCommonConfiguration()
        {
            _configuration = RestConfiguration.JsonDefault();
            _configuration.WithHeader("User-Agent", "RestFluencing Sample");
            _configuration.WithBaseUrl("https://api.github.com/");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        }
        private RestSession ParseRestSession(string data, RestConfiguration configuration)
        {
            var session = JsonSerializer.Deserialize <RestSession>(data);

            session.Configuration = configuration;

            return(session);
        }
 protected Dictionary <string, string> LoginConfigurationToHeaders(RestConfiguration configuration)
 {
     return(new Dictionary <string, string>
     {
         { "X-Parse-REST-API-Key", configuration.RestApiKey },
         { "X-Parse-Application-Id", configuration.ApplicationId }
     });
 }
 public TestBase()
 {
     Token             = TestConfigurationManager.GetToken();
     RestConfiguration = new RestConfiguration
     {
         AccessToken = Token
     };
 }
        public void TestConfiguration()
        {
            var rc = new RestConfiguration("http", "localhost", 30966, "api");

            var testUri = rc.CreateGetAll("Menu");

            Assert.AreEqual(testUri.AbsoluteUri, @"http://localhost:30966/api/Menu");
        }
Exemple #11
0
        public void WhenHasClientShouldSetTheReusableHttpApiClientFactory()
        {
            var config = new RestConfiguration();
            var client = new HttpClient();

            config.UsingWebApiClient(client);

            Assert.IsInstanceOfType(config.ClientFactory, typeof(ReUseHttpApiClientBuilder));
        }
Exemple #12
0
        public PortfolioService(RestConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _rest = new TinkoffRestService(configuration);
        }
        internal TinkoffRestService(RestConfiguration configuration) :
            base(configuration.BaseUrl)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            Configuration = configuration;
        }
        public void ValidationOk()
        {
            Mock <IThrottlingConfigurationValidator> throttlingConfigurationValidatorMock = new Mock <IThrottlingConfigurationValidator>();

            RestConfiguration configuration = CreateConfiguration();

            Assert.DoesNotThrow(() => new RestConfigurationValidator(throttlingConfigurationValidatorMock.Object).Validate(configuration));

            throttlingConfigurationValidatorMock.Verify(validator => validator.Validate(configuration.Throttling), Times.Once);
        }
Exemple #15
0
        private static void Validate(RestConfiguration restConfiguration)
        {
            if (restConfiguration == null)
            {
                throw new Exception("RestConfiguration cannot be null");
            }

            if (restConfiguration.SwaggerConfiguration == null)
            {
                throw new Exception("RestConfiguration.SwaggerConfiguration cannot be null");
            }
        }
        public static RestConfiguration Default()
        {
            // Setup Defaults
            var config = RestConfiguration.JsonDefault();

            config.WithBaseUrl("http://test.starnow.local/");

            // Setup Factory
            var factory = Factories.Default();

            config.ClientFactory = factory;
            return(config);
        }
        public void Setup()
        {
            // Setup Defaults
            var restDefaults = RestConfiguration.JsonDefault();

            restDefaults.WithBaseUrl("http://test.starnow.local/");
            _configuration = restDefaults;

            // Setup Factory
            var factory = Factories.Default();

            restDefaults.ClientFactory = factory;
            _factory = factory as TestApiFactory;
        }
        public void Test1()
        {
            var creds = new CredentialsProvider
            {
                Username = "******",
                Password = "******"
            };

            var apiConfig = new ApiConfiguration();

            var restClientConfig = new RestConfiguration(creds, apiConfig);
            var client           = new RestClient(restClientConfig);

            var result = client.Execute <string>(HttpVerb.GET, "action");
        }
        protected void Application_Start()
        {
            logger = new Logger();
            logger.Log("RestProxyNet starting.");

            restConfiguration = new RestConfiguration();
            logger.Log("RestConfiguration " + restConfiguration.Version);

            dbstore           = new DBStore();
            messageRepository = new MessageRepository();

            logger.DebugMode = "0";

            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
        internal TinkoffHttpService(RestConfiguration configuration, HttpClient httpClient = null)
            : base(configuration.BaseUrl, httpClient)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (string.IsNullOrWhiteSpace(configuration.AccessToken))
            {
                throw new ArgumentNullException(nameof(configuration.AccessToken));
            }

            Configuration = configuration;
        }
        public void EngineLogicAndHostingStarted()
        {
            Mock <IWatchdogThread> watchdogThreadMock = new Mock <IWatchdogThread>();

            bool startExecuted = false;

            watchdogThreadMock.Setup(p => p.StartChecking(It.IsAny <Action>(), It.IsAny <Action>())).Callback <Action, Action>
            (
                (startAction, stopAction) =>
            {
                startAction();     // force watchdog to start engine logic immediatelly
                startExecuted = true;
            }
            );
            watchdogThreadMock.Setup(p => p.StopChecking()).Callback(() => Assert.IsTrue(startExecuted));

            string       controllerValueString = Guid.NewGuid().ToString().ToLowerInvariant();
            const ushort HOST_PORT             = 9873;

            Container container = new Container();

            container.Options.DefaultScopedLifestyle = ScopedLifestyle.Flowing;
            container.Register <IFQueueController>(() => new TestController(controllerValueString), Lifestyle.Scoped);

            RestConfiguration restConfiguration = new RestConfiguration(HOST_PORT, new ThrottlingConfiguration(5, 5, 10, 15));

            EngineTester tester = new EngineTester(watchdogThreadMock.Object, new ControllerFactory(container), restConfiguration);

            tester.Start();

            Assert.AreEqual(1, tester.StartSpecificLogicCount);
            Assert.AreEqual(0, tester.StopSpecificLogicCount);

            WebClient client = new WebClient();

            Assert.AreEqual(controllerValueString, client.DownloadString($"http://127.0.0.1:{HOST_PORT}/{Engine.FQUEUE}/testC/testM"));

            tester.Stop();

            Assert.AreEqual(1, tester.StartSpecificLogicCount);
            Assert.AreEqual(0, tester.StopSpecificLogicCount); // because watchdog did not stop engine logic
        }
Exemple #22
0
 public RequestPicker()
 {
     RestConfiguration = new RestConfiguration();
 }
 public void Setup()
 {
     _configuration = RestConfigurationHelper.Default();
     _factory       = _configuration.ClientFactory as TestApiFactory;
 }
 public OperationService(
     RestConfiguration configuration, HttpClient client = null)
 {
     _http = new TinkoffHttpService(configuration, client);
 }
 /// <summary>
 /// Uses the standard HttpApiClient wrapper as the web client
 /// </summary>
 /// <param name="config">Configuration to apply to</param>
 /// <returns></returns>
 public static RestConfiguration UsingWebApiClient(this RestConfiguration config)
 {
     config.ClientFactory = new HttpApiClientBuilder();
     return(config);
 }
 /// <summary>
 /// Uses the JsonResponseDeserialiser to process the response.
 /// </summary>
 /// <param name="config">Configuration to apply to</param>
 /// <param name="loadSettings">Deserialiser settings to use (null for default)</param>
 /// <returns></returns>
 public static RestConfiguration UseJsonResponseDeserialiser(this RestConfiguration config, JsonLoadSettings loadSettings = null)
 {
     config.ResponseDeserialiser = new JsonResponseDeserialiser(loadSettings);
     return(config);
 }
Exemple #27
0
        static void Main(string[] args)
        {
            var token = File.ReadAllText("token.txt").Replace("\n", "").Replace("\t", "").Replace(" ", "");

            RestConfiguration = new RestConfiguration
            {
                AccessToken = token,
                BaseUrl     = "https://api-invest.tinkoff.ru/openapi/",
                SandboxMode = false
            };
            MarketService    = new MarketService(RestConfiguration);
            PortfolioService = new PortfolioService(RestConfiguration);
            OperationService = new OperationService(RestConfiguration);

            var result = PortfolioService.GetPortfolio().Result;

            Console.WriteLine("Портфель:");
            Console.WriteLine($"Тикер     \tКол-во   \tСредняя(FIFO)\tСредняя(Норм)\tДоход(FIFO)");
            foreach (var position in result.Positions)
            {
                var operationsOfOpenPosition = new[] { new { OperationType = ExtendedOperationType.BrokerCommission, Trade = new Trade() } }.ToList();
                operationsOfOpenPosition.Clear();
                var filter     = new OperationsFilter();
                filter.Figi     = position.Figi;
                filter.Interval = OperationInterval.Month;
                filter.To       = DateTime.Now;
                filter.From     = DateTime.Now.AddYears(-1);
                var operations = OperationService.Get(filter).Result.Operations;
                var buySellOperations = operations.Where(x => (x.OperationType == ExtendedOperationType.Buy || x.OperationType == ExtendedOperationType.Sell) && x.Status != OperationStatus.Decline)
                                        .SelectMany(x => x.Trades.Select(y => new { x.OperationType, Trade = y })).OrderByDescending(x => x.Trade.Date);

                var balance    = position.Balance;

                foreach (var operation in buySellOperations)
                {
                    balance = operation.OperationType == ExtendedOperationType.Buy ? (balance - operation.Trade.Quantity) : (balance + operation.Trade.Quantity);
                    operationsOfOpenPosition.Add(operation);
                    if (balance == 0)
                    {
                        break;
                    }
                }

                var averageValue      = 0m;
                var qty               = 0;
                var orderedOperations = operationsOfOpenPosition.OrderBy(x => x.Trade.Date);
                foreach (var operation in orderedOperations.OrderBy(x => x.Trade.Date))
                {
                    if (averageValue == 0m)
                    {
                        averageValue = operation.Trade.Price;
                        qty          = operation.Trade.Quantity;
                    }
                    else if (operation.OperationType == ExtendedOperationType.Buy)
                    {
                        averageValue = (averageValue * qty + operation.Trade.Price * operation.Trade.Quantity) / (qty + operation.Trade.Quantity);
                        qty         += operation.Trade.Quantity;
                    }
                    else
                    {
                        averageValue = (averageValue * qty - operation.Trade.Price * operation.Trade.Quantity) / (qty - operation.Trade.Quantity);
                        qty         -= operation.Trade.Quantity;
                    }
                }

                if (position.ExpectedYield.Value > 0)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                Console.WriteLine($"{position.Ticker,-15}\t{position.Balance, -8}\t{position.AveragePositionPrice.Value, -8}\t{averageValue,-8:0.00}\t{position.ExpectedYield?.Value,-8} {position.ExpectedYield?.Currency,-8}");

                //if(position.Ticker == "M")
                //{
                //    foreach(var operation in orderedOperations)
                //    {
                //        Console.WriteLine($"{position.Ticker} {operation.Trade.Date} {operation.OperationType} {operation.Trade.Price}x{operation.Trade.Quantity}={operation.Trade.Price*operation.Trade.Quantity} ");
                //    }
                //}

                //foreach (var operation in operations.Where(x=>x.OperationType != ExtendedOperationType.BrokerCommission && x.Status != OperationStatus.Decline))
                //{
                //   // Console.WriteLine($"{position.Ticker} {operation.Date} {operation.OperationType} {operation.Price} {operation.Quantity} {operation.Payment} {operation.Commission?.Value} {operation.Status}");
                //}
                //var buyOperations = operations.Where(x => x.OperationType == ExtendedOperationType.Buy && x.Status != OperationStatus.Decline).SelectMany(x=>x.Trades);
                //var sellOperations = operations.Where(x => x.OperationType == ExtendedOperationType.Sell && x.Status != OperationStatus.Decline).SelectMany(x => x.Trades);
                //Console.WriteLine($"{position.Ticker} count {buyOperations.Sum(x => x.Quantity) - sellOperations.Sum(x => x.Quantity)}");
            }
        }
 public EngineTester(IWatchdogThread watchdogThread, IControllerFactory controllerFactory, RestConfiguration restConfiguration)
     : base(watchdogThread, controllerFactory)
 {
     _restConfiguration = restConfiguration;
 }
Exemple #29
0
        private void StartHosting()
        {
            RestConfiguration restConfiguration = GetRestConfiguration();

            _webHost = WebHost.CreateDefaultBuilder(null)
                       .UseKestrel(options =>
            {
                options.AllowSynchronousIO = true;

                options.AddServerHeader = false;
                options.Limits.MaxConcurrentConnections = restConfiguration.Throttling.MaximumServerConnections;

                options.Listen(IPAddress.Any, restConfiguration.HostingPort);     //http://0.0.0.0:7081
            })
                       .ConfigureServices(services =>
            {
                services.AddLogging();

                services.AddMvc(o =>
                {
                    //o.EnableEndpointRouting = false;

                    o.RespectBrowserAcceptHeader = true;

                    o.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                }).AddApplicationPart(GetControllerAssembly());

                services.AddSingleton(_controllerFactory);

                services.AddSwaggerGen(c =>
                {
                    c.EnableAnnotations();
                    c.SwaggerDoc(FQUEUE, new OpenApiInfo {
                        Title = FQUEUE_CAPITALIZED, Version = "v1"
                    });
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                });
            })
                       .Configure(app =>
            {
                if (restConfiguration.Throttling.Enabled)
                {
                    app.UseMiddleware <ThrottlingMiddleware>(restConfiguration.Throttling);
                }

                app.UseRouting();
                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint($"/swagger/{FQUEUE}/swagger.json", FQUEUE_CAPITALIZED);
                });

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            })
                       .Build();

            _webHost.RunAsync();
        }
Exemple #30
0
 public void SetupCommonConfiguration()
 {
     _configuration = RestConfiguration.JsonDefault();
     _configuration.WithHeader("User-Agent", "RestFluencing Sample");
     _configuration.WithBaseUrl("https://api.github.com/");
 }