Пример #1
0
        /// <summary>
        /// Performs a GET request to the Discord REST API at the given endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="configureRequestBuilder">The request builder for the request.</param>
        /// <param name="allowNullReturn">Whether to allow null return values inside the creation result.</param>
        /// <param name="ct">The cancellation token for this operation.</param>
        /// <typeparam name="TEntity">The entity type to retrieve.</typeparam>
        /// <returns>A retrieval result which may or may not have succeeded.</returns>
        public async Task <Result <TEntity> > GetAsync <TEntity>
        (
            string endpoint,
            Action <RestRequestBuilder>?configureRequestBuilder = null,
            bool allowNullReturn = false,
            CancellationToken ct = default
        )
        {
            configureRequestBuilder ??= _ => { };

            var requestBuilder = new RestRequestBuilder(endpoint);

            configureRequestBuilder(requestBuilder);

            requestBuilder.WithMethod(HttpMethod.Get);

            try
            {
                using var request  = requestBuilder.Build();
                using var response = await _httpClient.SendAsync
                                     (
                          request,
                          HttpCompletionOption.ResponseHeadersRead,
                          ct
                                     );

                return(await UnpackResponseAsync <TEntity>(response, allowNullReturn, ct));
            }
            catch (Exception e)
            {
                return(e);
            }
        }
Пример #2
0
        /// <summary>
        /// Executes the search.
        /// </summary>
        /// <param name="searchCriteria">The search criteria.</param>
        /// <param name="includedProperties">The included properties.</param>
        /// <returns>Task&lt;RestResponse&lt;List&lt;TTargetEntity&gt;&gt;&gt;.</returns>
        protected virtual async Task <RestResponse <List <TTargetEntity> > > ExecuteSearch(SearchCriteria searchCriteria, IEnumerable <string> includedProperties = null)
        {
            //TODO: currently we expect TTargetEntity property names to be in SearchCriteria.  Consider if we should expect/map from TEntity?!?
            var request = RestRequestBuilder.BuildSearch(searchCriteria, includedProperties);

            return(await Context.ExecuteMessage <List <TTargetEntity> >(request));
        }
Пример #3
0
        /// <summary>
        /// Gets the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="orderBy">The order by.</param>
        /// <param name="includeProperties">The include properties.</param>
        /// <param name="noTracking">if set to <c>true</c> [no tracking].</param>
        /// <returns>Task&lt;IEnumerable&lt;TEntity&gt;&gt;.</returns>
        public virtual async Task <IEnumerable <TEntity> > Get(Expression <Func <TEntity, bool> > filter = null,
                                                               Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > orderBy = null,
                                                               IEnumerable <string> includeProperties = null, bool noTracking = false)
        {
            var request = RestRequestBuilder.BuildGetAll(includeProperties);

            var response = await Context.ExecuteMessage <List <TTargetEntity> >(request);

            var results = await MapTargetToLocal(response.Data);


            //
            // apply in memory filters
            //
            var query = results.AsQueryable();

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            return(query.ToList());
        }
Пример #4
0
        public override void Connect()
        {
            _publicKey = ((ServerParameterString)ServerParameters[0]).Value;
            _secretKey = ((ServerParameterPassword)ServerParameters[1]).Value;

            _baseWallet = ((ServerParameterEnum)ServerParameters[2]).Value;
            _tradeMode  = ((ServerParameterEnum)ServerParameters[3]).Value;
            _userId     = ((ServerParameterString)ServerParameters[4]).Value;

            if (_tradeMode == "Real")
            {
                _host       = "https://fx-api.gateio.ws";
                _baseUrlWss = "wss://fx-ws.gateio.ws/v4/ws";
            }
            if (_baseWallet == "BTC")
            {
                _wallet = "/btc";
            }

            _requestREST = new RestRequestBuilder();

            _cancelTokenSource = new CancellationTokenSource();

            StartMessageReader();

            _signer = new Signer(_secretKey);

            _wsSource = new WsSource(_baseUrlWss + _wallet);
            _wsSource.MessageEvent += WsSourceOnMessageEvent;
            _wsSource.Start();
        }
Пример #5
0
        /// <summary>
        /// Executes the delete.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>Task&lt;RestResponse&lt;dynamic&gt;&gt;.</returns>
        /// <exception cref="System.ApplicationException">Delete was not successfull</exception>
        protected RestResponse <dynamic> ExecuteDeleteSync(TTargetEntityId id)
        {
            var request = RestRequestBuilder.BuildDelete(id);

            //TODO: deputy returns string, but this code should be Deputy-agnostic
            RestResponse <dynamic> response = null;

            try
            {
                response = Context.ExecuteMessageSync <dynamic>(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException("Delete was not successfull");
                }
            }
            catch (RestException <dynamic> restEx)
            {
                // absorb not found errors...that is what delete is trying to accomplish
                // re-throw all other errors
                if (restEx.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(restEx.Response);
                }
                throw;
            }

            return(response);
        }
Пример #6
0
        private List <Trade> GetTrades(string security, DateTime endTime)
        {
            lock (_locker)
            {
                try
                {
                    var to = TimeManager.GetTimeStampSecondsToDateTime(endTime);

                    string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
                    var    headers   = new Dictionary <string, string>();
                    headers.Add("Timestamp", timeStamp);

                    RestRequestBuilder requestBuilder = new RestRequestBuilder();
                    requestBuilder.AddParam("contract", security);
                    requestBuilder.AddParam("limit", "1000");
                    requestBuilder.AddParam("to", to.ToString());

                    PublicUrlBuilder urlBuilder = new PublicUrlBuilder(_host, _path, _wallet);

                    var tradesJson = _requestREST.SendGetQuery("GET", "", urlBuilder.Build("/trades", requestBuilder), headers);

                    var tradesOut = JsonConvert.DeserializeObject <GfTrade[]>(tradesJson);

                    var oldTrades = CreateTradesFromJson(tradesOut);

                    return(oldTrades);
                }
                catch
                {
                    SendLogMessage(OsLocalization.Market.Message95 + security, LogMessageType.Error);

                    return(null);
                }
            }
        }
Пример #7
0
        public Response[] Process()
        {
            var collection = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;

            var builder = new RestRequestBuilder();

            var requests = builder.GetRequests(collection);

            return(Process(requests));
        }
Пример #8
0
        public void ProcessOneWayRequests()
        {
            var collection = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;

            var builder = new RestRequestBuilder();

            var requests = builder.GetOneWayRequests(collection);

            ProcessOneWayRequests(requests);
        }
Пример #9
0
        public Response[] Process()
        {
            var collection = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;

            var builder = new RestRequestBuilder();

            var requests = builder.GetRequests(collection);

            return Process(requests);
        }
Пример #10
0
        public void ProcessOneWayRequests()
        {
            var collection = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;

            var builder = new RestRequestBuilder();

            var requests = builder.GetOneWayRequests(collection);

            ProcessOneWayRequests(requests);
        }
Пример #11
0
        public ClientAuthModel SendRequestLoginPost(ClientSignInModel clientSignUpModel)
        {
            var response = new RestRequestBuilder(NewBookModelsUrl.GetBaseUrl("1"), NewBookModelsUrl.Auth.SingIn())
                           .AddParametersAsJsonRowInRequestBody(clientSignUpModel)
                           .AddMethodType(Method.POST)
                           .AddHeader("content-type", "application/json")
                           .AddRequestFormat(DataFormat.Json)
                           .Execute();

            return(JsonConvert.DeserializeObject <ClientAuthModel>(response.Content));
        }
Пример #12
0
        public SummonerDto GetSummonerByName(string summonerName, Platforms platform)
        {
            var restClient  = RestRequestBuilder.GetBaseClient(platform);
            var restRequest = RestRequestBuilder.GetBaseRequest(_endpoint + _byName + summonerName, _apiKey);

            restRequest.Method = Method.GET;
            var result = restClient.Execute(restRequest);
            var json   = result.Content;

            return(JsonConvert.DeserializeObject <SummonerDto>(json));
        }
Пример #13
0
        public RestReaderResponse <TResponse> PostRequest <TResponse, TRequest>(string uri, string contentType, TRequest requestData)
        {
            var preparer = new RequestPreparer(
                stream => webClientSerializerFactory
                .GetSerializer(contentType)
                .ToStream(stream, requestData),
                contentType
                );

            return(RestRequestBuilder.Request <TResponse>(webClientSerializerFactory, uri, preparer));
        }
Пример #14
0
        public UserModel SendRequestToGetClientInfo()
        {
            var response = new RestRequestBuilder(NewBookModelsUrl.GetBaseUrl("1"), NewBookModelsUrl.Profile.UpdateSelfInfo())
                           .AddMethodType(Method.GET)
                           .AddHeader("authorization", Context.Token)
                           .AddHeader("content-type", "application/json")
                           .AddRequestFormat(DataFormat.Json)
                           .Execute();

            return(JsonConvert.DeserializeObject <UserModel>(response.Content));
        }
Пример #15
0
        public void Should_resolve_non_indexed_type()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "request", typeof(TRequestType1).Name }
            };
            var requests = builder.GetRequests(collection);

            Assert.IsAssignableFrom(typeof(IRestTestClass), requests[0]);
        }
Пример #16
0
        public CurrentGameInfo GameBySummoner(Platforms platform, long summonerId)
        {
            var restClient  = RestRequestBuilder.GetBaseClient(platform);
            var restRequest = RestRequestBuilder.GetBaseRequest(_endPoint + _activeGame + summonerId, ApiKey);

            restRequest.Method = Method.GET;
            var result = restClient.Execute(restRequest);
            var json   = result.Content;

            return(JsonConvert.DeserializeObject <CurrentGameInfo>(json));
        }
Пример #17
0
        public List <LeaguePositionDto> GetPositionDto(Platforms platform, long summonerId)
        {
            var restClient  = RestRequestBuilder.GetBaseClient(platform);
            var restRequest = RestRequestBuilder.GetBaseRequest($"{_endpoint}{_leaguePositions}{summonerId}", _apikey);

            restRequest.Method = Method.GET;
            var response = restClient.Execute(restRequest);
            var json     = response.Content;

            return(JsonConvert.DeserializeObject <List <LeaguePositionDto> >(json));
        }
Пример #18
0
        public AvatarUploadModel SendRequestUploadUserAvatar(string filePath)
        {
            var response = new RestRequestBuilder(NewBookModelsUrl.GetBaseUrl(), NewBookModelsUrl.Images.ChangeAvatar())
                           .AddFile(filePath)
                           .AddMethodType(Method.POST)
                           .AddHeader("authorization", Context.Token)
                           .AddHeader("Content-type", "multipart/form-data")
                           .Execute();

            return(JsonConvert.DeserializeObject <AvatarUploadModel>(response.Content));
        }
Пример #19
0
        public List <ChampionMasteryDto> GetchampionMasteries(Platforms platform, long summonerId)
        {
            var restClient  = RestRequestBuilder.GetBaseClient(platform);
            var restRequest = RestRequestBuilder.GetBaseRequest($"{_endPoint}{_bySummoner}{summonerId}", _apiKey);

            restRequest.Method = Method.GET;
            var response = restClient.Execute(restRequest);
            var json     = response.Content;

            return(JsonConvert.DeserializeObject <List <ChampionMasteryDto> >(json));
        }
Пример #20
0
        public ClientProfileModel SendRequestUpdateProfileInformation(ClientProfileModel updateProfileModel)
        {
            var response = new RestRequestBuilder(NewBookModelsUrl.GetBaseUrl("1"), NewBookModelsUrl.Profile.Update())
                           .AddParametersAsJsonRowInRequestBody(updateProfileModel)
                           .AddMethodType(Method.PATCH)
                           .AddHeader("content-type", "application/json")
                           .AddHeader("authorization", Context.Token)
                           .AddRequestFormat(DataFormat.Json)
                           .Execute();

            return(JsonConvert.DeserializeObject <ClientProfileModel>(response.Content));
        }
Пример #21
0
        /// <summary>
        /// Existses the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        public virtual async Task <bool> Exists(Expression <Func <TEntity, bool> > filter)
        {
            var request = RestRequestBuilder.BuildExists();

            var response = await Context.ExecuteMessage <List <TTargetEntity> >(request);

            //TODO: use MapTargetToLocal methods
            var results = MapperRegistry.Map <List <TEntity> >(response.Data);
            var query   = results.AsQueryable();

            return(query.Any(filter));
        }
Пример #22
0
    public string SendRequestChangePassword(PasswordModel passwordModel)
    {
        var response = new RestRequestBuilder(NewBookModelsUrl.GetBaseUrl("1"), NewBookModelsUrl.Password.Change())
                       .AddParametersAsJsonRowInRequestBody(passwordModel)
                       .AddMethodType(RestSharp.Method.POST)
                       .AddRequestFormat(RestSharp.DataFormat.Json)
                       .AddHeader("authorization", Context.Token)
                       .AddHeader("cache-control", "no-cache")
                       .AddHeader("content-type", "application/json")
                       .Execute();

        return(response.Content);
    }
Пример #23
0
        public void Should_fail_when_no_request_key_is_passed()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "Name", "JoeBloggs" }
            };

            var exception = Record.Exception(() => builder.GetRequests(collection));

            Assert.NotNull(exception);
            Assert.IsAssignableFrom(typeof(InvalidOperationException), exception);
            Assert.True("At least one request type must be specified" == ((InvalidOperationException)exception).Message);
        }
Пример #24
0
        public void Should_fail_when_a_request_key_contains_invalid_characters()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "request_[0]", "Something" }
            };

            var exception = Record.Exception(() => builder.GetRequests(collection));

            Assert.NotNull(exception);
            Assert.IsAssignableFrom(typeof(InvalidOperationException), exception);
            Assert.True("An invalid request key has been specified." == ((InvalidOperationException)exception).Message);
        }
Пример #25
0
        public void Should_fail_with_non_indexed_duplicate_request_key()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "request", typeof(TRequestType1).Name },
                { "request", typeof(TRequestType2).Name }
            };

            var exception = Record.Exception(() => builder.GetRequests(collection));

            Assert.NotNull(exception);
            Assert.IsAssignableFrom(typeof(InvalidOperationException), exception);
            Assert.True("The name of the request type must be valid, and an index must be unique" == ((InvalidOperationException)exception).Message);
        }
Пример #26
0
        public void Should_fail_when_mixing_indexed_requests_with_non_indexed_requests()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "request[0]", typeof(TRequestType1).Name },
                { "request", typeof(TRequestType2).Name }
            };

            var exception = Record.Exception(() => builder.GetRequests(collection));

            Assert.NotNull(exception);
            Assert.IsAssignableFrom(typeof(InvalidOperationException), exception);
            Assert.True("Cannot mix indexed requests with non indexed requests" == ((InvalidOperationException)exception).Message);
        }
Пример #27
0
        public void Should_resolve_complex_type()
        {
            var builder    = new RestRequestBuilder();
            var collection = new NameValueCollection
            {
                { "request", typeof(TRequestType1).Name },
                { "Age", "27" },
                { "NestedClass_1Name", "Joe Bloggs" },
            };

            var requests = builder.GetRequests(collection);

            Assert.IsAssignableFrom(typeof(IRestTestClass), requests[0]);
            Assert.True(27 == ((IRestTestClass)requests[0]).Age);
            Assert.True("Joe Bloggs" == ((IRestTestClass)requests[0]).NestedProperty.Name);
        }
Пример #28
0
        /// <summary>
        /// Performs a GET request to the Discord REST API at the given endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="configureRequestBuilder">The request builder for the request.</param>
        /// <param name="ct">The cancellation token for this operation.</param>
        /// <returns>A retrieval result which may or may not have succeeded.</returns>
        public async Task <Result <Stream> > GetContentAsync
        (
            string endpoint,
            Action <RestRequestBuilder>?configureRequestBuilder = null,
            CancellationToken ct = default
        )
        {
            configureRequestBuilder ??= _ => { };

            var requestBuilder = new RestRequestBuilder(endpoint);

            configureRequestBuilder(requestBuilder);

            requestBuilder.WithMethod(HttpMethod.Get);

            foreach (var customization in _customizations)
            {
                customization.RequestCustomizer(requestBuilder);
            }

            try
            {
                var httpClient = _httpClientFactory.CreateClient("Discord");
                using var request  = requestBuilder.Build();
                using var response = await httpClient.SendAsync
                                     (
                          request,
                          HttpCompletionOption.ResponseHeadersRead,
                          ct
                                     );

                var unpackedResponse = await UnpackResponseAsync(response, ct);

                if (!unpackedResponse.IsSuccess)
                {
                    return(Result <Stream> .FromError(unpackedResponse));
                }

                var responseContent = await response.Content.ReadAsStreamAsync();

                return(Result <Stream> .FromSuccess(responseContent));
            }
            catch (Exception e)
            {
                return(e);
            }
        }
Пример #29
0
        private List <Candle> GetCandles(int oldInterval, string security, DateTime startTime, DateTime endTime)
        {
            lock (_locker)
            {
                try
                {
                    var needIntervalForQuery = CandlesCreator.DetermineAppropriateIntervalForRequest(oldInterval, _supportedIntervals, out var needInterval);

                    var from = TimeManager.GetTimeStampSecondsToDateTime(startTime);
                    var to   = TimeManager.GetTimeStampSecondsToDateTime(endTime);

                    string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
                    var    headers   = new Dictionary <string, string>();
                    headers.Add("Timestamp", timeStamp);

                    RestRequestBuilder requestBuilder = new RestRequestBuilder();
                    requestBuilder.AddParam("contract", security);
                    requestBuilder.AddParam("from", from.ToString());
                    requestBuilder.AddParam("to", to.ToString());
                    requestBuilder.AddParam("interval", needIntervalForQuery);

                    PublicUrlBuilder urlBuilder = new PublicUrlBuilder(_host, _path, _wallet);

                    var candlesJson = _requestREST.SendGetQuery("GET", "", urlBuilder.Build("/candlesticks", requestBuilder), headers);

                    var candlesOut = JsonConvert.DeserializeObject <GfCandle[]>(candlesJson);

                    var oldCandles = CreateCandlesFromJson(candlesOut);

                    if (oldInterval == needInterval)
                    {
                        return(oldCandles);
                    }

                    var newCandles = CandlesCreator.CreateCandlesRequiredInterval(needInterval, oldInterval, oldCandles);

                    return(newCandles);
                }
                catch
                {
                    SendLogMessage(OsLocalization.Market.Message95 + security, LogMessageType.Error);

                    return(null);
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Gets the by ids.
        /// </summary>
        /// <typeparam name="TId">The type of the t identifier.</typeparam>
        /// <param name="ids">The ids.</param>
        /// <param name="detach">if set to <c>true</c> [detach].</param>
        /// <returns>Task&lt;IEnumerable&lt;TEntity&gt;&gt;.</returns>
        /// <exception cref="System.NotImplementedException">Only {typeof(TEntityId).Name}</exception>
        public virtual async Task <IEnumerable <TEntity> > GetByIds <TId>(IEnumerable <TId> ids, bool detach = false)
        {
            if (typeof(TId) != typeof(TEntityId))
            {
                throw new NotImplementedException($"Only {typeof(TEntityId).Name} IDs are supported at this time.");
            }

            var maps = await GetMapByLocalIds(ids.Cast <TEntityId>());

            var externalIdLookup = maps.ToDictionary(x => x.ExternalId);

            var request = RestRequestBuilder.BuildGetByIds(externalIdLookup.Keys);

            var response = await Context.ExecuteMessage <List <TTargetEntity> >(request);

            return(await MapTargetToLocal(response.Data, externalIdLookup));
        }
Пример #31
0
        /// <summary>
        /// Performs a GET request to the Discord REST API at the given endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="configureRequestBuilder">The request builder for the request.</param>
        /// <param name="ct">The cancellation token for this operation.</param>
        /// <returns>A retrieval result which may or may not have succeeded.</returns>
        public async Task <Result <Stream> > GetContentAsync
        (
            string endpoint,
            Action <RestRequestBuilder>?configureRequestBuilder = null,
            CancellationToken ct = default
        )
        {
            configureRequestBuilder ??= _ => { };

            var requestBuilder = new RestRequestBuilder(endpoint);

            configureRequestBuilder(requestBuilder);

            requestBuilder.WithMethod(HttpMethod.Get);

            try
            {
                using var request  = requestBuilder.Build();
                using var response = await _httpClient.SendAsync
                                     (
                          request,
                          HttpCompletionOption.ResponseHeadersRead,
                          ct
                                     );

                var unpackedResponse = await UnpackResponseAsync(response, ct);

                if (!unpackedResponse.IsSuccess)
                {
                    return(Result <Stream> .FromError(new GenericError("Failed to unpack response."), unpackedResponse));
                }

                var responseContent = await response.Content.ReadAsStreamAsync();

                return(Result <Stream> .FromSuccess(responseContent));
            }
            catch (Exception e)
            {
                return(e);
            }
        }
Пример #32
0
        /// <summary>
        /// Performs a PUT request to the Discord REST API at the given endpoint.
        /// </summary>
        /// <param name="endpoint">The endpoint.</param>
        /// <param name="configureRequestBuilder">The request builder for the request.</param>
        /// <param name="allowNullReturn">Whether to allow null return values inside the creation result.</param>
        /// <param name="ct">The cancellation token for this operation.</param>
        /// <typeparam name="TEntity">The type of entity to create.</typeparam>
        /// <returns>A result which may or may not have succeeded.</returns>
        public async Task <Result <TEntity> > PutAsync <TEntity>
        (
            string endpoint,
            Action <RestRequestBuilder>?configureRequestBuilder = null,
            bool allowNullReturn = false,
            CancellationToken ct = default
        )
        {
            configureRequestBuilder ??= _ => { };

            var requestBuilder = new RestRequestBuilder(endpoint);

            configureRequestBuilder(requestBuilder);

            requestBuilder.WithMethod(HttpMethod.Put);

            foreach (var customization in _customizations)
            {
                customization.RequestCustomizer(requestBuilder);
            }

            try
            {
                var httpClient = _httpClientFactory.CreateClient("Discord");
                using var request  = requestBuilder.Build();
                using var response = await httpClient.SendAsync
                                     (
                          request,
                          HttpCompletionOption.ResponseHeadersRead,
                          ct
                                     );

                return(await UnpackResponseAsync <TEntity>(response, allowNullReturn, ct));
            }
            catch (Exception e)
            {
                return(e);
            }
        }