public async Task <IActionResult> Index([FromRoute] int id)
        {
            var query = new GraphQLRequest
            {
                Query     = @"
                query results ($pg: Int){
                  episodes (page: $pg)  {
                    info {
                        count
                        pages
                        next
                        prev
                    }
                    results {
                        id
                        name
                        air_date
                        episode
                    }
                  }
                }",
                Variables = new { pg = id }
            };

            ViewData["Page"] = id == 0 ? 1 : id;
            var response = await client.SendQueryAsync <EpisodeResponseType>(query);

            return(View(response.Data));
        }
        public async Task <IActionResult> Index([FromRoute] int id = 1)
        {
            var query = new GraphQLRequest
            {
                Query     = @"
                query results($pg: Int) {
                  characters (page: $pg)  {
                    info {
                        count
                        pages
                        next
                        prev
                    }
                    results {
                        name
                        created
                        id
                        image
                        species
                    }
                  }
                }",
                Variables = new { pg = id }
            };

            var response = await client.SendQueryAsync <CharacterResponseType>(query);

            return(View(response.Data));
        }
Esempio n. 3
0
        public async Task <List <ProductModel> > GetAllProductsAsync(CancellationToken cancellationToken = default)
        {
            var request = new GraphQLRequest
            {
                Query         = @"query getAll {
                                  products {
                                    items {
                                      id
                                      name
                                      price
                                      rating
                                      photoUrl
                                      description
                                      stock
                                      introduceAt
                                    }
                                  }
                                }",
                OperationName = "getAll"
            };

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

            return(response.Errors?.Any() ?? default ? default : response.Data.products.items);
        }
Esempio n. 4
0
        public static async Task <List <T> > ExceuteQueryReturnListAsyn <T>(string graphQLQueryType, string completeQueryString)
        {
            try
            {
                var request = new GraphQLRequest
                {
                    Query = completeQueryString
                };

                var response = await graphQLHttpClient.SendQueryAsync <object>(request);

                var stringResult = response.Data.ToString();
                stringResult = stringResult.Replace($"\"{graphQLQueryType}\":", string.Empty);
                stringResult = stringResult.Remove(0, 1);
                stringResult = stringResult.Remove(stringResult.Length - 1, 1);

                var result = JsonConvert.DeserializeObject <List <T> >(stringResult);

                return(result);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public async Task <Brand[]> GetBrands()
        {
            var request = new GraphQLRequest
            {
                Query = @"query { production { brands { id brandName } } }"
            };

            var response = await _client.SendQueryAsync <GraphQLResponse>(request);

            return(response.Data.Production.Brands);
        }
Esempio n. 6
0
        public async Task <string> FindBrew(string gtin)
        {
            var graphQlRequest = new GraphQLRequest
            {
                Query     = Queries.BrewByGtin,
                Variables = new { gtin },
            };

            var response = await m_client.SendQueryAsync(graphQlRequest, () => new { Id = "" });

            return(response.Data.Id);
        }
Esempio n. 7
0
        public async Task Can_Get_All_Theatres()
        {
            var query = new GraphQLHttpRequest
            {
                Query         = Query,
                OperationName = "AllTheatres",
            };

            var response = await _graphQlHttpClient.SendQueryAsync <TheatreResponseCollectionType>(query);

            response.Errors.Should().BeNull();
            response.Data.Theatres.Count.Should().BePositive();
        }
Esempio n. 8
0
        private async Task <string> FetchResult(CancellationToken cancellationToken)
        {
            string query = @"
                    query JobStatus($id: String!) {
                        job(id: $id) {
                            id
                            ready
                            status
                            result
                        }
                    }
                ";

            var request = new GraphQLRequest()
            {
                Query         = query,
                OperationName = "JobStatus",
                Variables     = new
                {
                    id = Id
                }
            };

            var response = await _graphQLHttpClient.SendQueryAsync <dynamic>(request, cancellationToken);

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

            var    job       = response.Data.job;
            string status    = (string)job.status;
            var    jobStatus = (JobStatus)Enum.Parse(typeof(JobStatus), status);

            if (jobStatus != JobStatus.SUCCESS)
            {
                throw new RuntimeException($"Job finished with status : {status}");
            }

            var result = job.result;

            if (result == null)
            {
                throw new RuntimeException("Job has finished with no results");
            }

            string output = (string)result;

            return(output);
        }
        public async Task <IActionResult> Index()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                query {
                    characters {
                        results {
                            id
                            name
                        }
                    }
                    episodes{
                        results {
                            id
                            name
                        }
                    }
                    locations {
                        results {
                            id
                            name
                        }
                    }
                }"
            };

            var response = await client.SendQueryAsync <FullResponseType>(query);

            return(View(response.Data));
        }
Esempio n. 10
0
        public async Task <List <TResult> > GetPages <TResponse, TResult>(GraphQLHttpRequest req, Func <TResponse, IEnumerable <TResult> > process)
        {
            PageInfo pageInfo = null;
            var      result   = new List <TResult>();

            do
            {
                if (pageInfo != null)
                {
                    ((QueryParams)req.Variables).After = pageInfo.EndCursor;
                }

                var res = await Policy
                          .WrapAsync(httpRetryPolicies)
                          .ExecuteAsync(() => client.SendQueryAsync <TResponse>(req));

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

                result.AddRange(process(res.Data));
                pageInfo = HasPagingInfo(res);
            }while (pageInfo != null && pageInfo.HasNextPage);

            return(result);
        }
        public async Task <string> Get()
        {
            var graphQLClient = new GraphQLHttpClient("http://*****:*****@"query{
                              materials{
                                id
                                name
                                description
                                gwp_z
                                concrete_scm_details{
                                  fly_ash
                                }
                                pct80_gwp_per_category_declared_unit
                                manufacturer{
                                  name
                                  alt_names
                                  location{
                                    country
                                    postalCode
                                  }
                                }
                                plant{
                                  name
                                  alt_names
                                  location{
                                    localName
                                  }
                                  owned_by{
                                    name
                                    location{
                                      country
                                    }
                                  }
                                }
                              }
                            }
                        "
            };

            var response = await graphQLClient.SendQueryAsync(request, () => new { materials = new List <Material>() });

            List <Material> materials = response.Data.materials;

            for (int i = 0; i < materials.Count; i++)
            {
                DebugOutput("Amount of materials: " + i);
            }

            if (response.Errors != null && response.Errors.Any())
            {
                throw new ApplicationException(response.Errors[0].Message);
            }

            return(JsonSerializer.Serialize(response, new JsonSerializerOptions {
                WriteIndented = true
            }));
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            /* var graphClient = new GraphQLClient("http://*****:*****@"query { viewer { login } }"
             * };
             * var test = graphClient.PostAsync(request).Result;*/

            using (var graphQLHttpClient = new GraphQLHttpClient("http://*****:*****@"bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiIzIiwidW5pcXVlX25hbWUiOiJ2aWN0b3J5IiwiZW1haWwiOiJ2aWN0b3JpYXJhZGV2YUB5YWhvby5jby5ueiIsImZpcnN0bmFtZSI6IlZpY3RvcmlhIiwibGFzdG5hbWUiOiJSYWRldmEiLCJyb2xlIjoiQWRtaW4iLCJuYmYiOjE1Mzk1MTU1MzYsImV4cCI6MTUzOTUxNzMzNiwiaWF0IjoxNTM5NTE1NTM2LCJpc3MiOiJTbWFydFN0b3JlcyIsImF1ZCI6IkN1c3RvbUNsaWVudCJ9.9XxG8i0WLGhRoWA97NDl98V4J3a9nCOIaH8CYoqN1OY");

                var result = graphQLHttpClient.SendQueryAsync(@"
					{
						orders {
							id
						}
					}
				"                ).Result;
                Console.WriteLine(result.Data);
                Console.ReadKey();
            }
        }
        public async Task <ClassificationCounts> GetReductionAsync(string subjectId)
        {
            GraphQLResponse response       = new GraphQLResponse();
            var             answersRequest = new GraphQLRequest
            {
                Query         = @"
                    query AnswerCount($workflowId: ID!, $subjectId: ID!) {
                      workflow(id: $workflowId) {
                        subject_reductions(subjectId: $subjectId, reducerKey: T0_Stats) {
                            data
                        }
                      }
                    }",
                OperationName = "AnswerCount",
                Variables     = new
                {
                    workflowId = Config.WorkflowId,
                    subjectId
                }
            };

            try
            {
                response = await GraphQLClient.SendQueryAsync(answersRequest);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Graph QL Error: {0}", e.Message);
            }
            return(ParseGraphQLResponse(response));
        }
        public async void SendQueryAsyncShouldPreserveUriParametersFact()
        {
            var endpoint = new Uri("http://localhost/api/graphql?code=my-secret-api-key");

            var handlerStub = new HttpHandlerStub();
            GraphQLHttpClientOptions options = new GraphQLHttpClientOptions()
            {
                EndPoint           = endpoint,
                HttpMessageHandler = handlerStub
            };
            GraphQLHttpClient systemUnderTest = new GraphQLHttpClient(options);

            var response = await systemUnderTest.SendQueryAsync(new GraphQLRequest
            {
                Query = @"
				{
					person(personID: ""1"") {
						name
					}
				}"
            });

            var actualRequestUri = handlerStub.LastRequest.RequestUri;
            var queryParams      = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(actualRequestUri.Query);

            Assert.True(queryParams.ContainsKey("code"), "Expected code query parameter to be preserved");
            Assert.Equal("my-secret-api-key", queryParams["code"]);
        }
Esempio n. 15
0
        private UserData GetUsers(GraphQLRequest request)
        {
            var response = _client.SendQueryAsync <object>(request);
            var result   = JsonConvert.DeserializeObject <UserData>(response.Result.Data.ToString());

            return(result);
        }
Esempio n. 16
0
        public async static Task NewOrdersQuery()
        {
            using (var graphQLClient = new GraphQLHttpClient("https://*****:*****@"
                    query {
                        newOrders {
                            id
                            addressLine1
                            addressLine2
                            amount
                        }
                }"
                };

                var newOrderResponse = await graphQLClient.SendQueryAsync <NewOrdersResponse>(newOrdersQuery);

                foreach (var newOrderDetail in newOrderResponse.Data.NewOrders)
                {
                    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~");
                    Console.WriteLine();
                    Console.WriteLine($"{nameof(NewOrderDetail.Id)}: {newOrderDetail.Id}");
                    Console.WriteLine($"{nameof(NewOrderDetail.AddressLine1)}: {newOrderDetail.AddressLine1}");
                    Console.WriteLine($"{nameof(NewOrderDetail.AddressLine2)}: {newOrderDetail.AddressLine2}");
                    Console.WriteLine($"{nameof(NewOrderDetail.Amount)}: {newOrderDetail.Amount}");
                    Console.WriteLine();
                    Console.WriteLine("~~~~~~~~~~~~~~~~~~~~");
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Gets the basic information about a server.
        /// </summary>
        /// <param name="serverUrl"></param>
        /// <returns></returns>
        public static async Task <ServerInfo> GetServerInfo(string serverUrl)
        {
            using var httpClient = new HttpClient();

            using var gqlClient = new GraphQLHttpClient(new GraphQLHttpClientOptions()
            {
                EndPoint = new Uri(new Uri(serverUrl), "/graphql")
            }, new NewtonsoftJsonSerializer(), httpClient);

            var request = new GraphQLRequest
            {
                Query = @" query { serverInfo { name company } }"
            };

            var response = await gqlClient.SendQueryAsync <ServerInfoResponse>(request);

            if (response.Errors != null)
            {
                return(null);
            }

            response.Data.serverInfo.url = serverUrl;

            return(response.Data.serverInfo);
        }
Esempio n. 18
0
        /// <summary>
        /// Executes the query and returns a responseEntity of type passed </summary>
        /// <param name="url"> </param>
        /// <param name="auth"> </param>
        /// <param name="query"> </param>
        /// <param name="Variables"> </param>
        /// <param name="tClass">
        /// @return </param>
        public async Task <GraphQLResponse <dynamic> > GraphqlExecute(string url, string query, IDictionary <string, object> variables, GraphQLOptions opts)
        {
            GraphQLHttpClient graphClient = new GraphQLHttpClient(url, new NewtonsoftJsonSerializer());

            graphClient.HttpClient.DefaultRequestHeaders.Add("User-Agent", this.userAgent);
            graphClient.HttpClient.DefaultRequestHeaders.Add("Authorization", await this.GetAuthorizationHeader(null));
            GraphQLRequestCamel request = new GraphQLRequestCamel(query, variables);

            try
            {
                return(await graphClient.SendQueryAsync <dynamic>(request));
            }
            catch (GraphQLHttpRequestException e)
            {
                if (opts == null)
                {
                    opts = defaultGraphQLOptions;
                }
                int retry = opts.Retry;
                // handle errors explicitly
                // extract the status from the error response
                // if 401 and retry > 0 then we can retry
                if (e.StatusCode == HttpStatusCode.Unauthorized && retry > 0)
                {
                    // unauthenticated request might be because token expired
                    // clear token and retry
                    this.ClearToken();
                    opts.Retry -= 1;
                    return(await this.GraphqlExecute(url, query, variables, opts));
                }

                // otherwise rethrow
                throw new TraceSdkException(e.Content);
            }
        }
Esempio n. 19
0
        static async Task Main(string[] args)
        {
            var options = new GraphQLHttpClientOptions
            {
                UseWebSocketForQueriesAndMutations = false,
                EndPoint       = new System.Uri("https://*****:*****@"
                query northwindQuery {
                      customers {
                        customerId, 
                        companyName,
                        contactName
                      }
                }"
            };

            var response = await client.SendQueryAsync <CustomerResponse>(request);

            var x = response.Data.Customers.FirstOrDefault();
        }
Esempio n. 20
0
        public async Task <dynamic> ExecuteQueryAsync(string query, Dictionary <string, object> args)
        {
            try
            {
                if (_client == null)
                {
                    _client = new GraphQLHttpClient(_endPointUrl);
                }

                dynamic eo = null;
                if (args != null && args.Count > 0)
                {
                    eo = args.Aggregate(new ExpandoObject() as IDictionary <string, Object>, (a, p) => { a.Add(p.Key, p.Value); return(a); });
                }

                var assentRequest = new GraphQLRequest()
                {
                    Query     = query,
                    Variables = eo
                };


                var graphQLResponse = await _client.SendQueryAsync(assentRequest);// SendQueryAsync(assentRequest);

                return(graphQLResponse.Data);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Esempio n. 21
0
        static async Task Main(string[] args)
        {
            var options = new GraphQLHttpClientOptions
            {
                EndPoint = new Uri("http://echo.somee.com/netflixgraph/graphql"),
            };

            var client = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());

            var query = "{ actionShows { casts } }";

            var request = new GraphQLHttpRequest
            {
                Query = query
            };

            var graphQLResponse = await client.SendQueryAsync <object>(request);


            var stringResult = graphQLResponse.Data.ToString();
            //stringResult = stringResult.Replace($"\"actionShows\":", string.Empty);
            //stringResult = stringResult.Remove(0, 1);
            //stringResult = stringResult.Remove(stringResult.Length - 1, 1);

            var result = JsonConvert.DeserializeObject <Data>(stringResult.ToString());

            for (int i = 0; i < result.ActionShows.Length; i++)
            {
                Console.WriteLine(result.ActionShows[i].Casts);
            }
            Console.Read();
        }
Esempio n. 22
0
        /// <summary>
        /// Performs a GraphQL query with the specified query text and returns the specified type.
        /// </summary>
        /// <typeparam name="T">The type of the result</typeparam>
        /// <param name="query">The query to perform</param>
        /// <param name="key">The key to get for the data</param>
        /// <returns>The result data</returns>
        protected async Task <T> QueryAsync <T>(string query, string key)
        {
            try
            {
                GraphQLHttpClient client = await this.GetGraphQLClient();

                GraphQLResponse <JObject> response = await client.SendQueryAsync <JObject>(new GraphQLRequest(query));

                Logger.Log(LogLevel.Debug, JSONSerializerHelper.SerializeToString(response));

                if (response.Errors != null && response.Errors.Length > 0)
                {
                    foreach (GraphQLError error in response.Errors)
                    {
                        Logger.Log(LogLevel.Error, $"GraphQL Query Error: {query} - {error.Message}");
                    }
                }

                if (response.Data != null && response.Data.ContainsKey(key))
                {
                    return(response.Data[key].ToObject <T>());
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
            return(default(T));
        }
Esempio n. 23
0
        static async Task Main(string[] args)
        {
            using var graphQLClient = new GraphQLHttpClient("http://wish.mirero.co.kr/api/graphql", new SystemTextJsonSerializer());

            var Request = new GraphQLRequest
            {
                Query = @"
                {
                    project(fullPath: ""mirero/team/solution-group/bootcamp"") {
                        name
                        issues(createdAfter: ""2020-07-10T00:00:00"") {
                            nodes {
                                title
                            }
                            pageInfo {
                                endCursor
                                hasNextPage
                            }
                        }
                    }
                }"
            };

            var graphQLResponse = await graphQLClient.SendQueryAsync <Response>(Request);

            Console.WriteLine(JsonSerializer.Serialize(graphQLResponse, new JsonSerializerOptions {
                WriteIndented = true
            }));
        }
Esempio n. 24
0
        public static async Task Main(string[] args)
        {
            using var graphQLClient = new GraphQLHttpClient("#TutajWkleićUrl");

            var testRequest = new GraphQLRequest {
                Query = @"
			    query {
			        getDistributorProduct(id: ""71889"") {
						id
						key
			            ean
			        }
			    }"            ,
            };
            var graphQLResponse = await graphQLClient.SendQueryAsync <GetDistributorProductResponse>(testRequest);

            Console.WriteLine("raw response:");
            Console.WriteLine(JsonSerializer.Serialize(graphQLResponse, new JsonSerializerOptions {
                WriteIndented = true
            }));

            Console.WriteLine();
            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }
        public static async Task <WarcraftLogsDamageResponse> GetResponse(string bearerToken, string combatEncounterId, WarcraftLogsDamageResponse.TableDataType tdt)
        {
            using (var graphQLClient = new GraphQLHttpClient(WARCRAFTLOGS_GRAPHQL_ENDPOINT,
                                                             new SystemTextJsonSerializer()))
            {
                graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {bearerToken}");

                var dpsChartRequest = new GraphQLRequest
                {
                    Query     = @"query($combatId: String, $tdt: TableDataType, $timestampEnd: Float){
                            reportData{
                                report(code: $combatId)
                                {
                                    table(dataType: $tdt, startTime: 0, endTime: $timestampEnd)
                                }
                            }
                        }",
                    Variables = new
                    {
                        combatId     = combatEncounterId,
                        tdt          = tdt.ToString(),
                        timestampEnd = (float)DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    }
                };

                var response = await graphQLClient.SendQueryAsync <WarcraftLogsDamageResponse>(dpsChartRequest);

                return(response.Data);
            }
        }
        private async Task GetLaunch()
        {
            Launch = null;
            var launchRequest = new GraphQLRequest
            {
                Query     = @"query getLaunch($id: ID!) {
                                      launch(id: $id) {
                                        id
                                        is_tentative
                                        upcoming
                                        mission_name
                                        links {
                                          article_link
                                          video_link
                                          flickr_images
                                          mission_patch
                                        }
                                        launch_date_utc
                                        details
                                      }
                                    }",
                Variables = new
                {
                    id = _launchId,
                }
            };

            var response = await _client.SendQueryAsync <Types.Query>(launchRequest);

            if (!(response.Errors ?? Array.Empty <GraphQLError>()).Any())
            {
                Launch = response.Data.launch;
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Gets basic user information given a token and a server.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task <UserInfo> GetUserInfo(string token, string url)
        {
            using var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

            using var gqlClient = new GraphQLHttpClient(new GraphQLHttpClientOptions()
            {
                EndPoint = new Uri(new Uri(url), "/graphql")
            }, new NewtonsoftJsonSerializer(), httpClient);

            var request = new GraphQLRequest
            {
                Query = @" query { user { name email id company } }"
            };

            var response = await gqlClient.SendQueryAsync <UserInfoResponse>(request);

            if (response.Errors != null)
            {
                return(null);
            }

            return(response.Data.user);
        }
Esempio n. 28
0
        private static async Task GetAllMovies(GraphQLHttpClient _gqlClient)
        {
            //Query q = new Query();
            string queryText = $"query{{movies{{movieID, title}}}}";
            string queryName = "movies";

            try
            {
                var request = new GraphQLRequest
                {
                    Query = queryText
                };

                var response = await _gqlClient.SendQueryAsync <object>(request);

                string result = response.Data.ToString();
                result = result.Replace($"\"{queryName}\":", string.Empty);
                result = result.Remove(0, 1);
                result = result.Remove(result.Length - 1, 1);

                var collection = JsonConvert.DeserializeObject <IEnumerable <Movie> >(result);

                foreach (Movie m in collection)
                {
                    Console.WriteLine("Movie ID: {0} - Title: {1}", m.MovieID, m.Title);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 29
0
        public async Task <IActionResult> GetCountries()
        {
            using (var graphQLClient = new GraphQLHttpClient("http://*****:*****@"{
                        countries {
                          geoname_id
                          code
                          name
                          iso_numeric
                          continent
                          continent_name
                          capital
                          population
                          currency_code
                          neighbours {
                            geoname_id
                            code
                            name
                            country_geoname_id
                          }
                        }
                      }",
                };

                return(Ok(await graphQLClient.SendQueryAsync <object>(query)));
            }
        }
        /// <summary>Returns all Pokemons</summary>
        public async Task <IEnumerable <Pokemon> > GetAllPokemons()
        {
            var query = new Query <Pokemon>("pokemons")
                        .AddArguments(new { first = 100 })
                        .AddField(p => p.Id)
                        .AddField(p => p.Number)
                        .AddField(p => p.Name)
                        .AddField(p => p.Height, hq => hq
                                  .AddField(h => h.Minimum)
                                  .AddField(h => h.Maximum)
                                  )
                        .AddField(p => p.Weight, wq => wq
                                  .AddField(w => w.Minimum)
                                  .AddField(w => w.Maximum)
                                  )
                        .AddField(p => p.Types);
            var request = new GraphQLRequest {
                Query = "{" + query.Build() + "}"
            };

            using var client = new GraphQLHttpClient(this.graphqlPokemonUrl, new NewtonsoftJsonSerializer());
            GraphQLResponse <PokemonsResponse> response = await client.SendQueryAsync <PokemonsResponse>(request);

            return(response.Data.Pokemons);
        }