public async Task <IEnumerable <HistoricalDatapointDTO> > GetPullRequestsHistoricalData()
        {
            // Create the request
            var req = new GraphQLRequest
            {
                Query     = GraphQLQueries.GetAllPullRequests,
                Variables = new GraphQLRequestVariables
                {
                    resultsPerPage = ResultsPerPage
                }
            };

            // Send the request
            // Fortunately the PullRequestNode is still valid even for the "simple" query which only gets a few values for each pull request.
            // The rest of the values in the PullRequestNode object will be null.
            var nodes = new List <PullRequestNode>();

            await GetPullRequestData(req, nodes);

            var firstPrDate = nodes.Min(prn => prn.createdAt);
            // Begin the loop at the date of the first PR.
            var date = new DateTimeOffset(firstPrDate.Year, firstPrDate.Month, firstPrDate.Day, 0, 0, 0, TimeSpan.Zero);

            var results = new List <HistoricalDatapointDTO>();

            // Aggregate by week.
            while ((date = date.AddDays(7)) <= DateTimeOffset.UtcNow)
            {
                var count = nodes.Count(prn => prn.createdAt <= date && (prn.closedAt == null || prn.closedAt >= date));
                results.Add(new HistoricalDatapointDTO()
                {
                    date  = date.ToUnixTimeMilliseconds(),
                    count = count
                });
            }

            return(results);
        }
Example #2
0
    // </SnippetEnumerateWithCancellation>

    // <SnippetGenerateAsyncStream>
    // <SnippetUpdateSignature>
    private static async IAsyncEnumerable <JToken> RunPagedQueryAsync(GitHubClient client,
                                                                      string queryText, string repoName)
    // </SnippetUpdateSignature>
    {
        var issueAndPRQuery = new GraphQLRequest
        {
            Query = queryText
        };

        issueAndPRQuery.Variables["repo_name"] = repoName;

        bool hasMorePages   = true;
        int  pagesReturned  = 0;
        int  issuesReturned = 0;

        // Stop with 10 pages, because these are large repos:
        while (hasMorePages && (pagesReturned++ < 10))
        {
            var postBody = issueAndPRQuery.ToJsonText();
            var response = await client.Connection.Post <string>(new Uri("https://api.github.com/graphql"),
                                                                 postBody, "application/json", "application/json");

            JObject results = JObject.Parse(response.HttpResponse.Body.ToString() !);

            int totalCount = (int)issues(results)["totalCount"] !;
            hasMorePages = (bool)pageInfo(results)["hasPreviousPage"] !;
            issueAndPRQuery.Variables["start_cursor"] = pageInfo(results)["startCursor"] !.ToString();
            issuesReturned += issues(results)["nodes"] !.Count();

            // <SnippetYieldReturnPage>
            foreach (JObject issue in issues(results)["nodes"] !)
            {
                yield return(issue);
            }
            // </SnippetYieldReturnPage>
        }

        JObject issues(JObject result) => (JObject)result["data"] !["repository"] !["issues"] !;
Example #3
0
        public async void WebsocketRequestCanBeCancelled()
        {
            var graphQLRequest = new GraphQLRequest(@"
				query Long {
					longRunning
				}"                );

            var chatQuery = Fixture.Server.Services.GetService <ChatQuery>();
            var cts       = new CancellationTokenSource();

            await ChatClient.InitializeWebsocketConnection();

            var request =
                ConcurrentTaskWrapper.New(() => ChatClient.SendQueryAsync(graphQLRequest, () => new { longRunning = string.Empty }, cts.Token));

            // Test regular request
            // start request
            request.Start();
            // wait until the query has reached the server
            chatQuery.WaitingOnQueryBlocker.Wait(1000).Should().BeTrue("because the request should have reached the server by then");
            // unblock the query
            chatQuery.LongRunningQueryBlocker.Set();
            // check execution time
            request.Invoke().Result.Data.longRunning.Should().Be("finally returned");

            // reset stuff
            chatQuery.LongRunningQueryBlocker.Reset();
            request.Clear();

            // cancellation test
            request.Start();
            chatQuery.WaitingOnQueryBlocker.Wait(1000).Should().BeTrue("because the request should have reached the server by then");
            cts.Cancel();
            request.Invoking().Should().Throw <TaskCanceledException>("because the request was cancelled");

            // let the server finish its query
            chatQuery.LongRunningQueryBlocker.Set();
        }
Example #4
0
        public async Task <GraphQLResponse <AllShops> > AllShops()
        {
            if (!IsLogged)
            {
                throw new Exception("Usuario não logado");
            }

            var req = new GraphQLRequest
            {
                Query = @"
                query {
                  allShops {
                    edges {
                      node {
                        name
                        pickupInstructions
                        pk
                        address {
                          pos
                          addressSt
                          addressData
                        }
                        chargeOptions {
                          label
                        }
                        externalId
                      }
                    }
                  }
                }"
            };

            var graphQLResponse = await _client.SendQueryAsync <AllShops>(req);

            IsLogged = true;

            return(graphQLResponse);
        }
        private async Task HandleRequestAsync(HttpContext context)
        {
            // first we need to get the request executor to be able to execute requests.
            IRequestExecutor requestExecutor = await GetExecutorAsync(context.RequestAborted);

            IHttpRequestInterceptor requestInterceptor = requestExecutor.GetRequestInterceptor();
            IErrorHandler           errorHandler       = requestExecutor.GetErrorHandler();

            HttpStatusCode?  statusCode = null;
            IExecutionResult?result;

            try
            {
                // next we parse the GraphQL request.
                GraphQLRequest request = _requestParser.ReadParamsRequest(context.Request.Query);
                result = await ExecuteSingleAsync(
                    context, requestExecutor, requestInterceptor, request);
            }
            catch (GraphQLRequestException ex)
            {
                // A GraphQL request exception is thrown if the HTTP request body couldn't be
                // parsed. In this case we will return HTTP status code 400 and return a
                // GraphQL error result.
                statusCode = HttpStatusCode.BadRequest;
                result     = QueryResultBuilder.CreateError(errorHandler.Handle(ex.Errors));
            }
            catch (Exception ex)
            {
                statusCode = HttpStatusCode.InternalServerError;
                IError error = errorHandler.CreateUnexpectedError(ex).Build();
                result = QueryResultBuilder.CreateError(error);
            }

            // in any case we will have a valid GraphQL result at this point that can be written
            // to the HTTP response stream.
            Debug.Assert(result is not null, "No GraphQL result was created.");
            await WriteResultAsync(context.Response, result, statusCode, context.RequestAborted);
        }
Example #6
0
        private async Task <GraphQLHttpRequest> BuildPostRequestAsync(HttpContext httpContext)
        {
            var req     = new GraphQLRequest();
            var httpReq = new GraphQLHttpRequest()
            {
                HttpContext = httpContext,
                HttpMethod  = "POST",
                Request     = req
            };
            // read body
            var reader = new StreamReader(httpContext.Request.Body);
            var body   = await reader.ReadToEndAsync();

            httpReq.ContentType = GetRequestContentType(httpContext.Request);
            switch (httpReq.ContentType)
            {
            case HttpContentType.GraphQL:
                req.Query = body;
                break;

            case HttpContentType.Json:
                var bodyObj = Deserialize <GraphQLRequest>(body);
                req.Query         = bodyObj.Query;
                req.OperationName = bodyObj.OperationName;
                req.Variables     = bodyObj.Variables;
                break;
            }
            // still check 'query' parameter in URL and overwrite query in body if found
            var urlQry    = httpContext.Request.Query;
            var urlQryPrm = urlQry["query"];

            if (!string.IsNullOrEmpty(urlQryPrm))
            {
                req.Query = urlQryPrm;
            }

            return(httpReq);
        }//method
Example #7
0
        public async Task <GraphQLResult> ExecuteRequest(GraphQLRequest request)
        {
            // FIXME: need cancelation tokens????
            //
            // probably can also use something like polly
            // https://github.com/App-vNext/Polly to retry on transient errors??

            try {
                using (var httpContent = CreateHttpContent(request)) {
                    // Base address should be set on the http client.
                    using (var response = await Client.PostAsync("", httpContent)) {
                        using (Stream responseStream = await response.Content.ReadAsStreamAsync()) {
                            if (response.IsSuccessStatusCode)
                            {
                                try {
                                    return(DeserializeJsonFromStream <GraphQLResult>(responseStream));
                                } catch (JsonSerializationException ex) {
                                    // try rereading the stream ... is this always safe?
                                    return(ResultBuilder.BuildGraphQLErrorResult(
                                               "Json Serialization Exception while reading GraphQL response",
                                               ex, request, await response.Content.ReadAsStringAsync()));
                                }
                            }
                            else
                            {
                                return(ResultBuilder.BuildGraphQLErrorResult(
                                           $"HTTP response is not success (code {response.StatusCode})",
                                           null, request, await response.Content.ReadAsStringAsync()));
                            }
                        }
                    }
                }
            } catch (Exception ex) { // Just catch WebException ??
                return(ResultBuilder.BuildGraphQLErrorResult(
                           "Exception while processing request",
                           ex, request, null));
            }
        }
        /// <summary>
        /// Executes request and returns load status
        /// </summary>
        /// <returns>Load status</returns>
        async public Task <string> Exec()
        {
            string query = @"
                    mutation LoadModel($model_id: Int!) {
                        modelLoad(modelId: $model_id) {
                            status
                        }
                    }
                ";

            GraphQLRequest request = new GraphQLRequest()
            {
                Query         = query,
                OperationName = "LoadModel",
                Variables     = new
                {
                    model_id = this.ModelId
                }
            };

            GraphQLResponse response = await this._graphQLHttpClient.SendMutationAsync(request);

            if (response.Errors != null)
            {
                throw new GraphQLException(response.Errors);
            }

            var modelLoad = response.Data.modelLoad;

            if (modelLoad == null)
            {
                throw new RuntimeException($"Cannot Load Model id : {this.ModelId}");
            }

            string status = (string)modelLoad.status;

            return(status);
        }
Example #9
0
        protected async Task <IBatchQueryResult> ExecuteOperationBatchAsync(
            HttpContext context,
            IRequestExecutor requestExecutor,
            IHttpRequestInterceptor requestInterceptor,
            GraphQLRequest request,
            IReadOnlyList <string> operationNames)
        {
            var requestBatch = new IReadOnlyQueryRequest[operationNames.Count];

            for (var i = 0; i < operationNames.Count; i++)
            {
                QueryRequestBuilder requestBuilder = QueryRequestBuilder.From(request);
                requestBuilder.SetOperation(operationNames[i]);

                await requestInterceptor.OnCreateAsync(
                    context, requestExecutor, requestBuilder, context.RequestAborted);

                requestBatch[i] = requestBuilder.Create();
            }

            return(await requestExecutor.ExecuteBatchAsync(
                       requestBatch, cancellationToken : context.RequestAborted));
        }
Example #10
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();


            var client = new GraphQLClient("https://swapi.apis.guru/");

            GraphQLRequest graphQLRequest = new GraphQLRequest
            {
                Query = @"query{
                           allFilms {
                                films
                                {
                                title
                                director
                                }
                            }
                        }"
            };
            GraphQLResponse graphQLResponse = await client.PostAsync(graphQLRequest);

            FilmData.ItemsSource = graphQLResponse.Data.allFilms.films.ToObject <List <Film> >();
        }
Example #11
0
        public async Task <JsonResult> Test1()
        {
            string query       = "query getAllCourses { getCourses { id name } }";
            var    heroRequest = new GraphQLRequest {
                Query = query, OperationName = "SchoolQuery"
            };

            var graphQLClient   = new GraphQLClient("http://localhost:13515/api/school");
            var graphQLResponse = await graphQLClient.PostAsync(heroRequest);

            string        json    = JsonConvert.SerializeObject(graphQLResponse.Data);
            var           result  = JsonConvert.DeserializeObject <Dictionary <string, List <Course> > >(json);
            List <Course> courses = new List <Course>();

            foreach (var obj in result.Values.ElementAt(0))
            {
                Course course = new Course();
                course.Id   = obj.Id;
                course.Name = obj.Name;
                courses.Add(course);
            }
            return(Json(courses, JsonRequestBehavior.AllowGet));
        }
Example #12
0
        public async void CanDoSerializationWithAnonymousTypes(int id, string name)
        {
            var graphQLRequest = new GraphQLRequest(@"
				query Human($id: String!){
					human(id: $id) {
						name
					}
				}

				query Droid($id: String!) {
				  droid(id: $id) {
				    name
				  }
				}"                ,
                                                    new { id = id.ToString() },
                                                    "Human");

            var response = await StarWarsClient.SendQueryAsync(graphQLRequest, () => new { Human = new { Name = string.Empty } })
                           .ConfigureAwait(false);

            Assert.Null(response.Errors);
            Assert.Equal(name, response.Data.Human.Name);
        }
        public async Task <int> InsertEmployee(EmployeeDto employeeDto)
        {
            var insertEmployeeMutation = @"mutation insertEmployee($employee: emp_Employee_insert_input!) {
                                                      insert_emp_Employee_one(object: $employee) {
                                                        id
                                                      }
                                                    }";

            var graphQlRequest = new GraphQLRequest
            {
                Query     = insertEmployeeMutation,
                Variables = new
                {
                    employee = employeeDto
                }
            };

            var response = await _graphQLHttpClient.SendMutationAsync <EmployeeInsertMutationResponse>(graphQlRequest);

            ValidateGraphResponse(response);

            return(response.Data.Employee?.Id ?? 0);
        }
Example #14
0
        public async Task <List <Owner> > GetAllOwners()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                        query ownersQuery{
                          owners {
                            id
                            name
                            address
                            accounts {
                              id
                              type
                              description
                            }
                          }
                        }",
            };

            var response = await _client.SendQueryAsync <ResponseOwnerCollectionType>(query);

            return(response.Data.Owners);
        }
Example #15
0
        public async Task GraphGlFunc()
        {
            var client = new GraphQLHttpClient("https://*****:*****@"query {
                           transportation {
                             cargoDescription
                             loadingDate
                             paymentType
                             routFrom
                             routFromCountry
                             routTo
                             routToCountry
                             vehicleType
                           }
                        }"
            };
            var response = await client.SendQueryAsync <GraphqlResponse>(request);

            this.transInfo = response.Data.transportation;
        }
Example #16
0
        public void GraphQl_QueryMeWithNonLoggedInUser_ShouldThrowException()
        {
            // arrange
            Setup();
            var heroRequest = new GraphQLRequest
            {
                Query = @"
                {
                    users {
                        me {
                            name
                        }
                    }
                }
            "
            };
            // action
            var    adminConnectionValue = (CoreDockerClient)_defaultRequestFactory.Value.GetConnection();
            Action testCall             = () => { adminConnectionValue.GraphQlPost(heroRequest).Wait(); };

            testCall.Should().Throw <Exception>().WithMessage("Authentication required.")
            .And.ToFirstExceptionOfException().GetType().Name.Should().Be("GraphQlResponseException");
        }
Example #17
0
        /// <summary>
        /// Method to perform a GraphQL request for a given query, before formatting the data into a given type
        /// </summary>
        /// <param name="query">The query to execute</param>
        /// <param name="objectType">Enum that specifies the target parse type</param>
        /// <returns>GraphQLResponse formatted in the type specified</returns>
        public async Task <object> Perform_GraphQL_Request(string query, GitHub_Model_Types objectType)
        {
            // Create a new GraphQL request with the target query
            var commitData = new GraphQLRequest
            {
                Query = query
            };

            // Create a new GraphQL client that refernces the GitHub API v4 endpoint as a base URL
            var client = new GraphQLClient("https://api.github.com/graphql");

            // Add a "User-Agent" header to identify the request
            client.DefaultRequestHeaders.Add("User-Agent", "request");

            // Add the GitHub API token included in secrets as a Bearer authorisation token. Required to authorise the request
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _config.Access_Token);

            // Get the request response
            var response = await client.PostAsync(commitData);

            // Convert the data to the target type and return
            return(Convert_GraphQL_Response_Data(response, objectType));
        }
Example #18
0
        public static async Task <T> QueryAsync <T>(string query)
        {
            var req = new GraphQLRequest();

            req.Query = query;
            try
            {
                var graphQLClient = new GraphQLClient("http://192.168.0.248:4000/graphql");
                var post          = await graphQLClient.PostAsync(req);

                Console.WriteLine("dostalem: " + post.Data.ToString());

//                JsonConvert.Des
                var deserialized = JsonConvert.DeserializeObject <T>(post.Data.ToString());
                return(deserialized);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GraphQl request failed: " + query + " msg: " + ex.Message);

                return(default(T));
            }
        }
        public async Task <List <Owner> > GetAllOwners()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                query ownersQuery{
                  owners {
                    id
                    name
                    address
                    accounts {
                      id
                      type
                      description
                    }
                  }
                }"
            };

            var response = await _client.PostAsync(query);

            return(response.GetDataFieldAs <List <Owner> >("owners"));
        }
Example #20
0
    public async Task <IActionResult> Tags()
    {
        try
        {
            var query = new GraphQLRequest(@"
                    query {
                      tags {
                        id
                        name
                      }
                    }
                ");

            var response = await _graphQLClientRef.SendQueryAsync <TagsType>(query);

            return(Ok(response.Data.Tags));
        }
        catch (Exception ex)
        {
            _logger.LogError("{exception}", ex);
            return(BadRequest());
        }
    }
Example #21
0
        public GraphQLRequest CreateWorkplan(Workplan workplan)
        {
            Dictionary <string, object> data = new Dictionary <string, object>
            {
                { "workpieceId", workplan.WorkpieceId },
            };

            var request = new GraphQLRequest
            {
                OperationName = null,
                Variables     = new
                {
                    _v0_workplan = data
                },
                Query = @"mutation ($_v0_workplan: WorkplanInputType!) {createWorkplan(workplan: $_v0_workplan) {
                id
                __typename
                }
                  }"
            };

            return(request);
        }
        public async Task <IActionResult> Post([FromBody] GraphQLRequest query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var inputs           = query.Variables.ToInputs();
            var executionOptions = new ExecutionOptions
            {
                Schema = _schema,
                Query  = query.Query,
                Inputs = inputs
            };

            var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

            if (result.Errors?.Count > 0)
            {
                return(BadRequest(result));
            }

            return(Ok(result));
        }
Example #23
0
        public async Task <List <TagModel> > GetTagsInUse()
        {
            var query = new GraphQLRequest
            {
                Query = @"query getTagsInUse {
	                        tagsInUse
                            { id name }
                        }"
            };

            var response = await _client.PostAsync(query);

            if (response.Errors is null)
            {
                return(response.GetDataFieldAs <List <TagModel> >("tagsInUse"));
            }

            var error = response.Errors.First();

            throw new GraphQLException(new GraphQLError {
                Message = $"Error: {error.Message}"
            });
        }
Example #24
0
        public async Task <IEnumerable <WeatherSummary> > GetWeatherSummariesFor(params long[] locationIds)
        {
            try
            {
                LocationAnalytics.HasNLocations(locationIds.Length);
                var graphQLRequest = new GraphQLRequest
                {
                    Query         = "query WeatherSummaries($location_ids: [Long]!) { summaries(location_ids: $location_ids)  { location temperature openWeatherIcon id date timezone } }",
                    OperationName = "WeatherSummaries",
                    Variables     = new { location_ids = locationIds.ToArray() }
                };

                var response = await AttemptAndRetry(() => graphQLHttpClient.SendQueryAsync(graphQLRequest)).ConfigureAwait(false);

                var forecasts = response.GetDataFieldAs <IEnumerable <WeatherSummary> >("summaries");
                return(forecasts);
            }
            catch (Exception exception)
            {
                Crashes.TrackError(exception);
                return(new WeatherSummary[0]);
            }
        }
        public async Task <List <WeatherForecast> > GetForecastListAsync()
        {
            using var graphQLClient = new GraphQLHttpClient(graphql_http, new NewtonsoftJsonSerializer());
            var allWeatherForecasts = new GraphQLRequest
            {
                Query         = @"
query allWeatherForecasts {
  allWeatherForecasts {
    nodes {
      id
      dt
      temperatureC
      summary
    }
  }
}
",
                OperationName = "allWeatherForecasts",
            };
            var graphQLResponse = await graphQLClient.SendQueryAsync <AllWeatherForecastsResponse>(allWeatherForecasts);

            return(graphQLResponse.Data.allWeatherForecasts.Nodes);
        }
Example #26
0
        private async Task <IReadOnlyList <IReadOnlyQueryRequest> > BuildBatchRequestAsync(
            HttpContext context,
            IServiceProvider services,
            GraphQLRequest request,
            IReadOnlyList <string> operationNames)
        {
            var queryBatch = new IReadOnlyQueryRequest[operationNames.Count];

            for (var i = 0; i < operationNames.Count; i++)
            {
                IQueryRequestBuilder requestBuilder =
                    QueryRequestBuilder.From(request)
                    .SetOperation(operationNames[i]);

                queryBatch[i] = await BuildRequestAsync(
                    context,
                    services,
                    requestBuilder)
                                .ConfigureAwait(false);
            }

            return(queryBatch);
        }
Example #27
0
        public async Task <IEnumerable <ReviewModel> > GetReviewByProductIdAsync(Guid id, CancellationToken cancellationToken = default)
        {
            var request = new GraphQLRequest
            {
                Query         = @"query ReviewsByProductQuery($productId: Guid!) {
                          reviews(productId: $productId) {
                            id
                            title
                            comment
                            productId
                          }
                        }",
                OperationName = "ReviewsByProductQuery",
                Variables     = new { productId = id }
            };

            var response = await _client.SendQueryAsync(
                request: request,
                defineResponseType : () => new { reviews = new List <ReviewModel>() },
                cancellationToken : cancellationToken);

            return(response.Errors?.Any() ?? default ? default : response.Data.reviews);
        }
Example #28
0
 public override bool InternalSendTip(string User, decimal amount)
 {
     try
     {
         //mutation{sendTip(userId:"", amount:0, currency:btc,isPublic:true,chatId:""){id currency amount}}
         string         userid   = "";
         GraphQLRequest LoginReq = new GraphQLRequest
         {
             Query = "mutation{sendTip(userId:\"" + userid + "\", amount:" + amount.ToString("0.00000000", System.Globalization.NumberFormatInfo.InvariantInfo) + ", currency:" + Currency.ToLower() + ",isPublic:true,chatId:\"14939265-52a4-404e-8a0c-6e3e10d915b4\"){id currency amount}}"
         };
         GraphQLResponse Resp = GQLClient.PostAsync(LoginReq).Result;
         return(Resp.Data.sendTip.id.Value != null);
     }
     catch (WebException e)
     {
         if (e.Response != null)
         {
             string sEmitResponse = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
             Parent.updateStatus(sEmitResponse);
         }
     }
     return(false);
 }
        public async Task <ProductModel> AddProduct(ProductInputModel product)
        {
            var query = new GraphQLRequest
            {
                Query     = @" mutation($productIn: ProductInput!) {
                              createProduct(productInput: $productIn) {
                                id
                                name
                                price
                                photoFileName
                                description
                              }
                            }",
                Variables = new
                {
                    productIn = product
                }
            };

            var respone = await _client.PostAsync(query);

            return(respone.GetDataFieldAs <ProductModel>("createProduct"));
        }
Example #30
0
        public Task <TreeNode> GetNodeAsync(int Id)
        {
            TreeNode aux_node = null;

            GraphQLRequest request = new GraphQLRequest
            {
                Query = @"
                        {
                          node(id:" + Id + @") {
                            id,
                            parentId,
                            label,
                            date
                            }
                        }"
            };

            var graphQLClient = new GraphQLClient("http://localhost:6000/api/nodes");

            System.Console.WriteLine($"-- to POST {Id}");
            try
            {
                var graphQLResponse = graphQLClient.PostAsync(request).GetAwaiter().GetResult();
                //var graphQLResponse = graphQLClient.Post(request);
                var x = graphQLResponse.Data.node;
                System.Console.WriteLine(x);
                aux_node = x.ToObject <TreeNode>();
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }

            System.Console.WriteLine("-- after POST");

            return(Task.FromResult(aux_node));
        }