public override void Save(DocumentWriter writer) { base.Save(writer); writer.Write(Name); writer.Write(items.Count); foreach (var item in items) { writer.Write(item); } }
public void AssertQuery(string query, ExecutionResult executionResult) { var executer = new DocumentExecuter(); var writer = new DocumentWriter(); var runResult = executer.Execute(Schema, query, null); var writtenResult = writer.Write(runResult); var expectedResult = writer.Write(executionResult); writtenResult.ShouldEqual(expectedResult); }
public void WithDecimal_HasCorrectType() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(EchoSchema)); var query = @"{ __type(name : ""Input_Schema1Request"") { name fields{ name type{ kind name } } }"; var exec = new DocumentExecuter(new AntlrDocumentBuilder(), new DocumentValidator()); var result = exec.ExecuteAsync(schema, null, query, null).Result; var writer = new DocumentWriter(indent: true); var writtenResult = writer.Write(result.Data); var errors = result.Errors?.FirstOrDefault(); Assert.Null(errors?.Message); Assert.True(writtenResult.Contains("decimal")); }
public async Task Invoke(HttpContext httpContext) { var logger = httpContext.RequestServices.GetService <ILogger <GraphQlMiddleware> >(); HttpRequest request = httpContext.Request; HttpResponse response = httpContext.Response; // GraphQL HTTP only supports GET and POST methods. if (request.Method != "GET" && request.Method != "POST") { response.Headers.Add("Allow", "GET, POST"); response.StatusCode = 405; return; } // Check authorization if (options.AuthorizationPolicy != null) { var authorizationService = httpContext.RequestServices.GetRequiredService <IAuthorizationService>(); var authzResult = await authorizationService.AuthorizeAsync(httpContext.User, options.AuthorizationPolicy); if (!authzResult.Succeeded) { await httpContext.ForbidAsync(); return; } } GraphQlParameters parameters = await GetParametersAsync(request); ISchema schema = schemaProvider.Create(httpContext.RequestServices); var result = await executer.ExecuteAsync(executionOptions => { executionOptions.Schema = schema; executionOptions.Query = parameters.Query; executionOptions.OperationName = parameters.OperationName; executionOptions.Inputs = parameters.GetInputs(); executionOptions.CancellationToken = httpContext.RequestAborted; executionOptions.ComplexityConfiguration = options.ComplexityConfiguration; executionOptions.UserContext = httpContext; executionOptions.ExposeExceptions = options.ExposeExceptions; ConfigureDocumentExecutionListeners(executionOptions, executionListeners); }); if (result.Errors?.Count > 0) { logger.LogError("GraphQL Result {Errors}", result.Errors); } var writer = new DocumentWriter(indent: options.FormatOutput); var json = writer.Write(result); response.StatusCode = 200; response.ContentType = "application/json; charset=utf-8"; await response.WriteAsync(json); }
public void FieldDescription_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(AsyncSchema)); var query = @"{ __schema{ types{ name, fields { name description } } } }"; var exec = new DocumentExecuter(new GraphQLDocumentBuilder(), new DocumentValidator(), new ComplexityAnalyzer()); var result = exec.ExecuteAsync(schema, null, query, null).Result; var writer = new DocumentWriter(indent: true); var writtenResult = writer.Write(result.Data); var errors = result.Errors?.FirstOrDefault(); Assert.Null(errors?.Message); Assert.True(writtenResult.Contains("{VerifyComment}")); }
public static void QuerySuccess(GraphQL.Types.Schema schema, string query, string expected) { var exec = new DocumentExecuter(new AntlrDocumentBuilder(), new DocumentValidator()); var result = exec.ExecuteAsync(schema, null, query, null).Result; var writer = new DocumentWriter(indent: true); var writtenResult = writer.Write(result.Data); var expectedResult = writer.Write(CreateQueryResult(expected).Data); var errors = result.Errors?.FirstOrDefault(); //for easy debugging var allTypes = schema.AllTypes; Assert.Null(errors?.Message); Assert.Equal(expectedResult, writtenResult); }
static void Main(string[] args) { var executer = new DocumentExecuter(); var writer = new DocumentWriter(); //var query = @"{ // artists { // name // } // }"; var query = "{ artist(name: \"Alice Cooper\") { name } }"; var root = new QueryRoot(); var schema = new Schema <QueryRoot>(); var result = executer.ExecuteAsync(config => { config.Schema = schema; config.Root = root; config.Query = query; }); Console.WriteLine(writer.Write(result.Result)); }
public async Task <string> ExecuteQueryAsync(string query) { query = query .Replace("{\"query\":\"", string.Empty) .Replace("\",\"variables\":{}}", string.Empty); ExecutionResult result = await executer.ExecuteAsync(new RouteInspectorSchema(), logger, query, null); return(writer.Write(result)); }
public string Execute(string query) { var schema = new StarWarsSchema(type => (GraphType)Services.Get(type)); IDocumentExecuter documentExecutor = new DocumentExecuter(new AntlrDocumentBuilder(), new DocumentValidator()); IDocumentWriter writer = new DocumentWriter(indent: true); var runResult = documentExecutor.ExecuteAsync(schema, null, query, null); var writtenResult = writer.Write(runResult); return(writtenResult); }
public static void Main(string[] args) { Document doc = new Document(); DocumentWriter writer = new DocumentWriter(doc); // Write to the document: writer.Write("Hello world!"); writer.Backspace(); doc.PrintDocument(); // Hello world writer.Undo(); doc.PrintDocument(); // Hello world! writer.Redo(); doc.PrintDocument(); // Hello world writer.Write(" Goodbye!"); doc.PrintDocument(); // Hello world Goodbye! writer.Undo(); doc.PrintDocument(); // Hello world writer.Undo(); doc.PrintDocument(); // Hello world! }
public static async Task <string> Execute( this ISchema schema, string query, object rootObject = null, Inputs inputs = null, string operationName = null) { var executer = new DocumentExecuter(); var writer = new DocumentWriter(); var result = await executer.ExecuteAsync(schema, rootObject, query, operationName, inputs); return(writer.Write(result)); }
private static async Task RunTests() { TestDataGenerator.InitializeDb(); var writer = new DocumentWriter(true); var results = new List <ExecutionResult>(); results.Add(await RunTest("Baseline", _ => _.Baseline())); results.Add(await RunTest("DataLoader", _ => _.DataLoader())); results.Add(await RunTest("BatchResolver", _ => _.BatchResolver())); for (var i = 0; i < results.Count; i++) { File.WriteAllText("log/result" + i + ".json", writer.Write(results[i])); } }
public void Can_read() { var docs = new List <Document> { new Document(0, new List <Field> { new Field(0, "title", "rambo"), new Field(0, "_id", "0") }), new Document(1, new List <Field> { new Field(1, "title", "rocky"), new Field(1, "_id", "1") }), new Document(2, new List <Field> { new Field(2, "title", "rocky 2"), new Field(2, "_id", "2") }) }; var fileName = Path.Combine(Dir, "DocumentReaderTests.Can_read"); var blocks = new Dictionary <int, BlockInfo>(); using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) using (var writer = new DocumentWriter(fs, Compression.GZip)) { foreach (var doc in docs) { blocks.Add(doc.Id, writer.Write(doc)); } } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip)) { var doc = reader.Get(new[] { blocks[2] }); Assert.AreEqual(2, doc.First().Id); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip)) { var doc = reader.Get(new[] { blocks[1] }); Assert.AreEqual(1, doc.First().Id); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip)) { var doc = reader.Get(new[] { blocks[0] }); Assert.AreEqual(0, doc.First().Id); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip)) { var ds = reader.Get(blocks.Values.OrderBy(b => b.Position).ToList()).ToList(); Assert.AreEqual(3, docs.Count); Assert.IsTrue(ds.Any(d => d.Id == 0)); Assert.IsTrue(ds.Any(d => d.Id == 1)); Assert.IsTrue(ds.Any(d => d.Id == 2)); } }
public string SerializeResult(ExecutionResult result) { return(_documentWriter.Write(result)); }
private static void RunQuery() { var query = @" { droids { droidId name primaryFunction appearsIn friends { name ... on Human { humanId appearsIn } } } }"; var executer = new DocumentExecuter(); var writer = new DocumentWriter(true); string output1, output2; // Example 1 - QueryRoot. using (var root = new QueryRoot()) using (var schema = new Schema <QueryRoot>()) { var result = executer.ExecuteAsync(schema, root, query, null).Result; output1 = writer.Write(result); Console.WriteLine("Example 1 output (QueryRoot):"); Console.WriteLine("-----------------------------"); Console.WriteLine(output1); Console.WriteLine(); } // Example 2 - DbContext. // I get the feeling there are reasons why wouldn't // want to do this but for simple scenarios it seems to suffice. using (var db = new StarWarsContext()) using (var schema = new Schema <StarWarsContext>()) { var result = executer.ExecuteAsync(schema, db, query, null).Result; output2 = writer.Write(result); Console.WriteLine("Example 2 output (StarWarsContext):"); Console.WriteLine("-----------------------------------"); Console.WriteLine(output2); Console.WriteLine(); } // Confirm we got the same result, just 'cause... var defaultColor = Console.ForegroundColor; if (output1 == output2) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("✓ Outputs are the same"); } else { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("× Outputs are different"); } Console.ForegroundColor = defaultColor; }
public override void Draw(DocumentWriter writer) { const int shadingPatternType = 2; // tiling pattern = 1 void WriteNumberHighPrecision(float v) { // WriteNumber isn't high precision enough, only supports 2 decimal places :( var bytes = Encoding.ASCII.GetBytes($"{v} "); writer.Write(bytes); } writer.WriteBeginObject(); writer.WriteDictionaryOpen(); { writer.WriteName(NamePatternTypeBytes); writer.WriteNumber(shadingPatternType); writer.WriteName(NameMatrixBytes); writer.WriteArrayOpen(); { _shadingColor.DrawMatrix(WriteNumberHighPrecision); } writer.WriteArrayClose(); writer.WriteName(NameShadingBytes); writer.WriteDictionaryOpen(); { writer.WriteName(NameShadingTypeBytes); writer.WriteNumber((int)_shadingColor.ShadingType); writer.WriteName(NameColorSpaceBytes); _shadingColor.Stops[0].Color.ColorSpace.DrawColorSpace(writer); writer.WriteName(NameCoordsBytes); writer.WriteArrayOpen(); { _shadingColor.DrawCoordinates(WriteNumberHighPrecision); } writer.WriteArrayClose(); writer.WriteName(NameExtendBytes); writer.WriteArrayOpen(); { writer.WriteBoolean(true); writer.WriteBoolean(true); } writer.WriteArrayClose(); writer.WriteName(NameFunctionBytes); if (_shadingColor.Stops.Count > 2) { WriteStitchingFunction(writer); } else if (_shadingColor.Stops.Count == 2) { var stop1 = _shadingColor.Stops[0]; var stop2 = _shadingColor.Stops[1]; WriteLinearColorInterpolationFunction(writer, stop1.Color, stop2.Color); } else { throw new InvalidOperationException($"Expected two or more color stops"); } } writer.WriteDictionaryClose(); } writer.WriteDictionaryClose(); writer.WriteEndObject(); }
public override void Save(DocumentWriter writer) { base.Save(writer); writer.Write(Points); }
public override async Task Invoke(IOwinContext context) { try { var schema = _applicationContext.ApplicationCache.RuntimeCache.GetCacheItem <UmbracoSchema>( "Our.Umbraco.GraphQL::Schema", () => new UmbracoSchema( _applicationContext.Services.ContentTypeService, _applicationContext.Services.MemberTypeService, _options ) ); if (false == context.Request.Path.HasValue) { var request = context.Get <GraphQLRequest>("Our.Umbraco.GraphQL::Request"); switch (context.Request.Method) { case "POST": if (request == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("POST body missing."); return; } break; default: context.Response.StatusCode = 405; await context.Response.WriteAsync("Server supports only POST requests."); return; } IEnumerable <Task <ExecutionResult> > requests = request.Select(requestParams => { try { string query = requestParams.Query; string operationName = requestParams.OperationName; Inputs variables = requestParams.Variables; return(new DocumentExecuter() .ExecuteAsync(x => { x.CancellationToken = context.Request.CallCancelled; //x.ComplexityConfiguration = new ComplexityConfiguration(); x.ExposeExceptions = _options.Debug; //x.FieldMiddleware.Use<InstrumentFieldsMiddleware>(); x.FieldNameConverter = new DefaultFieldNameConverter(); x.Inputs = variables; x.OperationName = operationName; x.Query = query; //x.Root = x.Schema = schema; x.UserContext = new UmbracoGraphQLContext( context.Request.Uri, _applicationContext, UmbracoContext.Current, _options ); })); } catch (Exception) { throw; } }); var responses = await Task.WhenAll(requests); context.Response.ContentType = "application/json"; var writer = new DocumentWriter(); if (false == request.IsBatched) { var response = writer.Write(responses[0]); await context.Response.WriteAsync(response); } else { var response = writer.Write(responses); await context.Response.WriteAsync(response); } } else if (context.Request.Path.ToString() == "/schema") { using (var schemaPrinter = new SchemaPrinter(schema)) { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync(schemaPrinter.Print()); } } } catch (Exception ex) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 500; if (_options.Debug) { await context.Response.WriteAsync(ex.ToString()); } else { await context.Response.WriteAsync("Internal server error"); } } }
public void Can_read() { var docs = new List <Document> { new Document(0, new List <Field> { new Field("title", "rambo"), new Field("_id", "0") }), new Document(1, new List <Field> { new Field("title", "rocky"), new Field("_id", "1") }), new Document(2, new List <Field> { new Field("title", "rocky 2"), new Field("_id", "2") }) }; var fileName = Path.Combine(CreateDir(), "DocumentReaderTests.Can_read"); var blocks = new Dictionary <int, BlockInfo>(); var keyIndex = docs[0].ToKeyIndex(); var revKeyIndex = keyIndex.ToDictionary(x => x.Value, y => y.Key); using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) using (var writer = new DocumentWriter(fs, Compression.GZip)) { foreach (var doc in docs) { blocks.Add(doc.Id, writer.Write(doc.ToTableRow(keyIndex))); } } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex)) { var doc = reader.Read(new[] { blocks[2] }); Assert.AreEqual("rocky 2", doc.First().Fields["title"].Value); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex)) { var doc = reader.Read(new[] { blocks[1] }); Assert.AreEqual("rocky", doc.First().Fields["title"].Value); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex)) { var doc = reader.Read(new[] { blocks[0] }); Assert.AreEqual("rambo", doc.First().Fields["title"].Value); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs, Compression.GZip, revKeyIndex)) { var ds = reader.Read(blocks.Values.OrderBy(b => b.Position).ToList()).ToList(); Assert.AreEqual(3, docs.Count); Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rambo")); Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rocky")); Assert.IsTrue(ds.Any(d => d.Fields["title"].Value == "rocky 2")); } }
public override async Task Invoke(IOwinContext context) { try { var schema = _applicationContext.ApplicationCache.RuntimeCache.GetCacheItem <UmbracoSchema>( "Our.Umbraco.GraphQL::Schema", () => new UmbracoSchema( _applicationContext.Services.ContentTypeService, _applicationContext.Services.MemberTypeService, _options ) ); if (false == context.Request.Path.HasValue) { var request = context.Get <GraphQLRequest>("Our.Umbraco.GraphQL::Request"); switch (context.Request.Method) { case "POST": if (request == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("POST body missing."); return; } break; default: context.Response.StatusCode = 405; await context.Response.WriteAsync("Server supports only POST requests."); return; } IEnumerable <Task <ExecutionResult> > requests = request.Select(async requestParams => { string query = requestParams.Query; string operationName = requestParams.OperationName; string accessToken = context.Request.Query["accessToken"]; Inputs variables = requestParams.Variables; var validationRules = new List <IValidationRule> { new RequiresAuthValidationRule() }; var start = DateTime.Now; MiniProfiler.Start(); var errors = new ExecutionErrors(); var result = await _documentExecutor .ExecuteAsync(x => { x.CancellationToken = context.Request.CallCancelled; //x.ComplexityConfiguration = new ComplexityConfiguration(); x.ExposeExceptions = _options.Debug; if (_options.EnableMetrics) { x.EnableMetrics = true; x.FieldMiddleware.Use <InstrumentFieldsMiddleware>(); x.FieldMiddleware.Use <MiniProfilerFieldsMiddleware>(); } x.FieldNameConverter = new DefaultFieldNameConverter(); x.Inputs = variables; x.OperationName = operationName; x.Query = query; //x.Root = x.Schema = schema; x.UserContext = new UmbracoGraphQLContext( context.Request.Uri, _applicationContext, UmbracoContext.Current, _options, accessToken, out errors ); x.ValidationRules = validationRules; }); // Save any of our errors reported by our authentication stuff in UserContext if (errors.Any()) { if (result.Errors != null) { result.Errors.Concat(errors); } else { result.Errors = errors; } } if (_options.EnableMetrics && result.Errors == null) { result.EnrichWithApolloTracing(start); if (result.Extensions == null) { result.Extensions = new Dictionary <string, object>(); } result.Extensions["miniProfiler"] = JObject.FromObject(MiniProfiler.Current, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); } MiniProfiler.Stop(); return(result); }); var responses = await Task.WhenAll(requests); context.Response.ContentType = "application/json"; if (false == request.IsBatched) { var response = _documentWriter.Write(responses[0]); await context.Response.WriteAsync(response); } else { var response = _documentWriter.Write(responses); await context.Response.WriteAsync(response); } } else if (context.Request.Path.ToString() == "/schema") { using (var schemaPrinter = new SchemaPrinter(schema)) { context.Response.ContentType = "text/plain"; await context.Response.WriteAsync(schemaPrinter.Print()); } } } catch (Exception ex) { context.Response.ContentType = "text/plain"; context.Response.StatusCode = 500; if (_options.Debug) { await context.Response.WriteAsync(ex.ToString()); } else { await context.Response.WriteAsync("Internal server error"); } } }
public void Can_read() { var docs = new List <Document> { new Document(new Dictionary <string, string> { { "title", "rambo" }, { "_id", "0" } }), new Document(new Dictionary <string, string> { { "title", "rocky" }, { "_id", "1" } }), new Document(new Dictionary <string, string> { { "title", "rocky 2" }, { "_id", "2" } }) }; var fileName = Path.Combine(Setup.Dir, "DocumentReaderTests.Can_read"); var blocks = new Dictionary <int, BlockInfo>(); using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) using (var writer = new DocumentWriter(fs)) { var index = 0; foreach (var doc in docs) { doc.Id = index++; blocks.Add(doc.Id, writer.Write(doc)); } } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs)) { var doc = reader.Get(new[] { blocks[2] }); Assert.That(doc.First().Id, Is.EqualTo(2)); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs)) { var doc = reader.Get(new[] { blocks[1] }); Assert.That(doc.First().Id, Is.EqualTo(1)); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs)) { var doc = reader.Get(new[] { blocks[0] }); Assert.That(doc.First().Id, Is.EqualTo(0)); } using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) using (var reader = new DocumentReader(fs)) { var ds = reader.Get(blocks.Values.OrderBy(b => b.Position)).ToList(); Assert.That(docs.Count, Is.EqualTo(3)); Assert.IsTrue(ds.Any(d => d.Id == 0)); Assert.IsTrue(ds.Any(d => d.Id == 1)); Assert.IsTrue(ds.Any(d => d.Id == 2)); } }
public void Save(DocumentWriter writer) { writer.Write(Color); writer.Write(LineWeight); writer.Write((int)DashStyle); }