public async Task AddClassErrorFilter()
        {
            // arrange
            ISchema schema = Schema.Create("type Query { foo: String }",
                                           c => c.BindResolver(
                                               ctx =>
            {
                throw new Exception("Foo");
            }).To("Query", "foo"));

            var options = new QueryExecutionOptions
            {
                IncludeExceptionDetails = false
            };

            IQueryExecutor executor = schema.MakeExecutable(builder =>
                                                            builder.UseDefaultPipeline(options)
                                                            .AddErrorFilter <DummyErrorFilter>());

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ foo }");

            // assert
            result.MatchSnapshot();
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


            services.AddScoped <IRepository, InMemoryRepository>();
            // this enables you to use DataLoader in your resolvers.
            services.AddDataLoaderRegistry();

            // Add GraphQL Services
            var queryExecutionOptions = new QueryExecutionOptions
            {
                TracingPreference = TracingPreference.OnDemand
            };

            if (_environment.IsDevelopment())
            {
                queryExecutionOptions.TracingPreference       = TracingPreference.Always;
                queryExecutionOptions.IncludeExceptionDetails = true;
                _logger.LogInformation(" *** LogInformation: In DEV Environment");
            }

            // Create our schema
            var schemaDef = File.ReadAllText("schema.graphql");
            var schema    = Schema.Create(schemaDef, ConfigureSchema);

            services.AddGraphQL(schema, queryExecutionOptions);
        }
Example #3
0
 public async Task <List <TModel> > GetAllAsync(QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         return((await unitOfWork.Connection.GetAllAsync <TModel>(ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds)).ToList());
     }
 }
Example #4
0
 public List <TModel> GetAll(QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         return(unitOfWork.Connection.GetAll <TModel>(ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds).ToList());
     }
 }
Example #5
0
 public virtual async Task <bool> UpdateAsync(TModel model, QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         return(await unitOfWork.Connection.UpdateAsync(model, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds));
     }
 }
Example #6
0
 public Task <TModel> GetByIdAsync(TKey id, QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         return(unitOfWork.Connection.GetAsync <TModel>(id, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds));
     }
 }
Example #7
0
        public static IServiceCollection AddCustomGraphQl(this IServiceCollection collection)
        {
            var customOptions = new QueryExecutionOptions
            {
                ForceSerialExecution = true,
            };

            return(collection
                   .AddGraphQL(
                       provider => SchemaBuilder.New()
                       .AddAuthorizeDirectiveType()
                       // To restrict max number of fields in one page
                       .AddType(new PaginationAmountType(100))
                       .ModifyOptions(e =>
            {
                e.DefaultBindingBehavior = BindingBehavior.Explicit;
                e.UseXmlDocumentation = true;
            })
                       .BindClrType <Unit, VoidType>()
                       .BindClrType <TimeSpan, TimeSpanType>()
                       .AddMutationType <GraphQlMutations>()
                       .AddQueryType <GraphQlQueries>()
                       .AddServices(provider)
                       .Create(),
                       builder => builder
                       .Use <CustomGraphQlExceptionHandlingMiddleware>()
                       .UseDefaultPipeline())
                   .AddSingleton <IExecutionStrategyOptionsAccessor>(provider => customOptions));
        }
Example #8
0
 public virtual async Task <bool> DeleteAsync(IEnumerable <TKey> ids, QueryExecutionOptions options = null)
 {
     foreach (var id in ids)
     {
         await DeleteAsync(id, options);
     }
     return(true);
 }
Example #9
0
 public virtual bool Delete(IEnumerable <TKey> ids, QueryExecutionOptions options = null)
 {
     foreach (var id in ids)
     {
         Delete(id, options);
     }
     return(true);
 }
Example #10
0
 public virtual async Task <bool> AddAsync(IEnumerable <TModel> models, QueryExecutionOptions options = null)
 {
     foreach (var model in models)
     {
         await AddAsync(model, options);
     }
     return(true);
 }
Example #11
0
 public virtual bool Add(IEnumerable <TModel> models, QueryExecutionOptions options = null)
 {
     foreach (var model in models)
     {
         Add(model, options);
     }
     return(true);
 }
        private static IQueryExecutionOptionsAccessor CreateOptions()
        {
            var options = new QueryExecutionOptions();

            options.ExecutionTimeout = TimeSpan.FromSeconds(30);

            return(options);
        }
Example #13
0
 public override sealed long Add(TModel model, QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         model.Id = unitOfWork.Connection.Insert(model, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds);
         return(model.Id);
     }
 }
Example #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //services.AddGraphQL(SchemaBuilder.New());

            /*
             * This is an alternative approach (workaround) to fix this behavior
             */
            #region Workaround

            Func <IServiceProvider, ISchema> factory = s => SchemaBuilder.New()
                                                       .AddServices(s)
                                                       .AddType <AuthorType>()
                                                       .AddType <BookType>()
                                                       .AddQueryType <Query>()
                                                       .Create();

            var opts = new QueryExecutionOptions {
            };

            services.AddSingleton(sp =>
            {
                var d = sp.GetRequiredService <DiagnosticListener>();
                var o = sp.GetServices <IDiagnosticObserver>();

                BindingFlags flags   = BindingFlags.NonPublic | BindingFlags.Instance;
                CultureInfo culture  = null;
                var instantiatedType = Activator.CreateInstance(typeof(QueryExecutionDiagnostics), flags, null, new object[] { d, o }, culture);
                return(instantiatedType as QueryExecutionDiagnostics);
            });

            QueryExecutionBuilder.New()
            .AddDefaultServices(opts)
            .UseRequestTimeout()
            .UseExceptionHandling()


            .UseQueryParser()
            .UseNoCachedQueryError()
            .UseValidation()
            .UseOperationResolver()
            .UseMaxComplexity()
            .UseOperationExecutor()
            .Populate(services);

            services.AddSingleton(factory);
            services.AddSingleton <IIdSerializer, IdSerializer>()
            .AddGraphQLSubscriptions();
            services.AddJsonQueryResultSerializer().AddJsonArrayResponseStreamSerializer();

            services.AddSingleton <IBatchQueryExecutor, BatchQueryExecutor>();

            /* END */
            #endregion

            services.AddApplicationInsightsTelemetry();
        }
Example #15
0
        public virtual async Task <TKey> AddAsync(TModel model, QueryExecutionOptions options = null)
        {
            using (var unitOfWork = ConnectionManager.Connect())
            {
                await unitOfWork.Connection.InsertAsync(model, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds);

                return(model.Id);
            }
        }
        private IQueryValidator CreateValidator()
        {
            var services = new ServiceCollection();
            var options  = new QueryExecutionOptions();

            services.AddQueryValidation(options);
            services.AddDefaultValidationRules();

            return(services.BuildServiceProvider()
                   .GetRequiredService <IQueryValidator>());
        }
Example #17
0
        public bool DeleteWhere(Expression <Func <TModel, bool> > where, QueryExecutionOptions options = null)
        {
            var(whereClauseSql, whereClauseParameters) = WhereClauseCompiler.ToSql(where, language: WhereClauseCompiler.Language.MYSQL);
            var parameters = new DynamicParameters(whereClauseParameters);

            using (var unitOfWork = ConnectionManager.Connect())
            {
                var rowsDeleted = unitOfWork.Connection.Execute($"DELETE FROM {TableName} WHERE {whereClauseSql}", parameters, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds);

                return(rowsDeleted >= 0);
            }
        }
Example #18
0
        public override sealed bool Delete(IEnumerable <long> ids, QueryExecutionOptions options = null)
        {
            var(whereClauseSql, whereClauseParameters) = WhereClauseCompiler.ToSql <TModel>(x => ids.Contains(x.Id), language: WhereClauseCompiler.Language.MYSQL);
            var parameters = new DynamicParameters(whereClauseParameters);

            using (var unitOfWork = ConnectionManager.Connect())
            {
                var deletedRows = unitOfWork.Connection.Execute($"DELETE FROM {TableName} WHERE {whereClauseSql}", parameters, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds);

                return(deletedRows >= 0);
            }
        }
        public async Task ExecuteOperationMiddleware_Mutation_ExecutedSerially()
        {
            // arrange
            var state = 0;

            var schema = Schema.Create(
                FileResource.Open("MutationExecutionSchema.graphql"),
                cnf =>
            {
                cnf.BindResolver(() => state)
                .To("Query", "state");
                cnf.BindResolver(() => state)
                .To("CurrentState", "theNumber");
                cnf.BindResolver(
                    ctx => state = ctx.Argument <int>("newNumber"))
                .To("Mutation", "changeTheNumber");
            });

            DocumentNode query = Parser.Default.Parse(
                FileResource.Open("MutationExecutionQuery.graphql"));

            OperationDefinitionNode operation = query.Definitions
                                                .OfType <OperationDefinitionNode>()
                                                .FirstOrDefault();

            var request = new QueryRequest("{ a }").ToReadOnly();

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default));

            var context = new QueryContext(schema, services, request)
            {
                Document  = query,
                Operation = operation
            };

            var options          = new QueryExecutionOptions();
            var strategyResolver = new ExecutionStrategyResolver(options);

            var middleware = new ExecuteOperationMiddleware(
                c => Task.CompletedTask,
                strategyResolver,
                new Cache <DirectiveLookup>(10));

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.NotNull(context.Result);
            context.Result.Snapshot();
        }
Example #20
0
        public virtual bool Update(IEnumerable <TModel> models, QueryExecutionOptions options = null)
        {
            bool result = true;

            foreach (var model in models)
            {
                if (result)
                {
                    result = result && Update(model, options);
                }
            }
            return(result);
        }
Example #21
0
        public virtual async Task <bool> UpdateAsync(IEnumerable <TModel> models, QueryExecutionOptions options = null)
        {
            bool result = true;

            foreach (var model in models)
            {
                if (result)
                {
                    result = result && await UpdateAsync(model, options);
                }
            }
            return(result);
        }
Example #22
0
 public virtual async Task <bool> DeleteAsync(TKey id, QueryExecutionOptions options = null)
 {
     using (var unitOfWork = ConnectionManager.Connect())
     {
         if (await unitOfWork.Connection.DeleteAsync(new TModel {
             Id = id
         }, ConnectionManager.GetCurrentTransaction(), options?.TimeoutInSeconds))
         {
             return(true);
         }
     }
     return(false);
 }
        public async Task FilterOnlyNullRefExceptions()
        {
            // arrange
            ISchema schema = Schema.Create(
                "type Query { foo: String bar: String }",
                c =>
            {
                // will be handled by the default filter logic
                c.BindResolver(
                    ctx =>
                {
                    throw new Exception("Foo");
                }).To("Query", "foo");

                // will be handled by the custom filter logic
                c.BindResolver(
                    ctx =>
                {
                    throw new NullReferenceException("Foo");
                }).To("Query", "bar");
            });

            var options = new QueryExecutionOptions
            {
                IncludeExceptionDetails = false,
                ExecutionTimeout        = TimeSpan.FromMinutes(10)
            };

            IQueryExecutor executor = schema.MakeExecutable(builder =>
                                                            builder.UseDefaultPipeline(options)
                                                            .AddErrorFilter(error =>
            {
                if (error.Exception is NullReferenceException)
                {
                    return(error.WithCode("NullRef"));
                }
                return(error);
            }));

            // act
            IExecutionResult result =
                await executor.ExecuteAsync("{ foo bar }");

            // assert
            result.MatchSnapshot(o =>
                                 o.IgnoreField("Errors[0].Exception")
                                 .IgnoreField("Errors[1].Exception"));
        }
Example #24
0
        public List <TModel> GetWhere(Expression <Func <TModel, bool> > where, QueryExecutionOptions options = null)
        {
            var limit = options?.ResultLimit;

            if (limit.HasValue && limit.Value <= 0)
            {
                return(new List <TModel>());
            }

            var(query, parameters) = BuildGetWhereQuery(where, options);

            using (var unitOfWork = ConnectionManager.Connect())
            {
                return(unitOfWork.Connection.Query <TModel>(query, parameters, ConnectionManager.GetCurrentTransaction(), commandTimeout: options?.TimeoutInSeconds).ToList());
            }
        }
Example #25
0
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment   = environment;

            _queryExecutionOptions = new QueryExecutionOptions
            {
                MaxExecutionDepth       = 32,
                MaxOperationComplexity  = 256,
                IncludeExceptionDetails = Environment.IsDevelopment(),
                ExecutionTimeout        = new TimeSpan(0, 0, 10),
                ForceSerialExecution    = true
            };

            // register API types
            _schema = SchemaBuilder.New()
                      .BindClrType <int, IntType>()
                      .BindClrType <string, StringType>()
                      .BindClrType <bool, BooleanType>()
                      .AddQueryType(x => x.Name("Query"))
                      .AddMutationType(x => x.Name("Mutation"))
                      .AddEnumType <AuthorizationErrorCodes>(x => x.BindValuesImplicitly())
                      .AddEnumType <UserSignUpErrorCode>(x => x.BindValuesImplicitly())
                      .AddEnumType <UserSignInErrorCode>(x => x.BindValuesImplicitly())
                      .AddType(new PaginationAmountType(64))
                      .AddType <MailType>()
                      .AddType <MailQueryType>()
                      .AddType <MailMutationType>()
                      .AddType <MailFilterInputType>()
                      .AddType <MailCreateInputType>()
                      .AddType <MailUpdateInputType>()
                      .AddType <MailDeleteInputType>()
                      .AddType <UserMutationType>()
                      .AddType <UserSignUpPayloadType>()
                      .AddType <UserSignInPayloadType>()
                      .AddType <MailGroupType>()
                      .AddType <MailGroupQueryType>()
                      .AddType <MailGroupMutationType>()
                      .AddType <MailGroupCreateInputType>()
                      .AddType <MailGroupUpdateInputType>()
                      .AddType <MailGroupDeleteInputType>()
                      .AddType <MailGroupMailType>()
                      .AddType <MailGroupMailMutationType>()
                      .ModifyOptions(x => x.DefaultBindingBehavior = BindingBehavior.Explicit)
                      .Create();
        }
Example #26
0
        public void AddGraphQL_ServicesSchemaConfigOptions()
        {
            // arrange
            var services = new ServiceCollection();
            var options  = new QueryExecutionOptions();

            // act
            ServiceCollectionExtensions.AddGraphQL(
                services,
                c => c.Options.StrictValidation = false,
                options);

            // assert
            services.Select(t => ReflectionUtils.GetTypeName(t.ServiceType))
            .OrderBy(t => t, StringComparer.Ordinal)
            .ToArray()
            .MatchSnapshot();
        }
        public async Task ExecuteOperationMiddleware_Mutation_ExecutedSerially()
        {
            // arrange
            var state = 0;

            var schema = Schema.Create(
                FileResource.Open("MutationExecutionSchema.graphql"),
                cnf =>
            {
                cnf.BindResolver(() => state)
                .To("Query", "state");
                cnf.BindResolver(() => state)
                .To("CurrentState", "theNumber");
                cnf.BindResolver(
                    ctx => state = ctx.Argument <int>("newNumber"))
                .To("Mutation", "changeTheNumber");
            });

            DocumentNode query = Parser.Default.Parse(
                FileResource.Open("MutationExecutionQuery.graphql"));

            OperationDefinitionNode operationNode = query.Definitions
                                                    .OfType <OperationDefinitionNode>()
                                                    .FirstOrDefault();

            var operation = new Operation
                            (
                query,
                operationNode,
                new VariableValueBuilder(
                    schema,
                    operationNode)
                .CreateValues(new Dictionary <string, object>()),
                schema.MutationType,
                null
                            );

            IReadOnlyQueryRequest request = new QueryRequest("{ a }");

            var observable = new DiagnosticListener("Foo");

            var services = new DictionaryServiceProvider(
                new KeyValuePair <Type, object>(
                    typeof(IErrorHandler),
                    ErrorHandler.Default),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticListener),
                    observable),
                new KeyValuePair <Type, object>(
                    typeof(DiagnosticSource),
                    observable));

            var context = new QueryContext
                          (
                schema,
                services.CreateRequestServiceScope(),
                request,
                fs => fs.Field.Middleware
                          )
            {
                Document  = query,
                Operation = operation
            };

            var options          = new QueryExecutionOptions();
            var strategyResolver = new ExecutionStrategyResolver(options);

            var diagnostics = new QueryExecutionDiagnostics(
                new DiagnosticListener("Foo"),
                new IDiagnosticObserver[0],
                TracingPreference.Never);

            var middleware = new ExecuteOperationMiddleware(
                c => Task.CompletedTask,
                strategyResolver,
                new Cache <DirectiveMiddlewareCompiler>(10),
                diagnostics);

            // act
            await middleware.InvokeAsync(context);

            // assert
            Assert.NotNull(context.Result);
            context.Result.Snapshot();
        }
Example #28
0
 public void ExecuteIntersectionQuery(BoundingBox bounds, FeatureDataTable table, QueryExecutionOptions options)
 {
     throw new NotImplementedException();
 }
Example #29
0
 public IFeatureDataReader ExecuteIntersectionQuery(BoundingBox bounds, QueryExecutionOptions options)
 {
     throw new NotImplementedException();
 }
Example #30
0
 public IAsyncResult BeginExecuteIntersectionQuery(BoundingBox bounds, FeatureDataTable table,
                                                   QueryExecutionOptions options, AsyncCallback callback,
                                                   object asyncState)
 {
     throw new NotImplementedException();
 }