public void GenerateDefinitions(DirectoryInfo targetDir = null) { if (targetDir == null) { targetDir = new DirectoryInfo(System.IO.Path.Combine(this._parent.Files.Folder.FullName, "Schemas")); } if (!targetDir.Exists) { targetDir.Create(); } SchemaGenerator generator = new SchemaGenerator(this._parent.Config, this._parent) { }; foreach (var item in this._parent.Get <EntityDefinition>()) { generator.Add(item); } foreach (var item in this._parent.Get <RelationshipDefinition>()) { generator.Add(item); } generator.GenerateTo(targetDir); }
public void GenerateDocument_GeneratesDocumentWithSingleMessage() { // Arrange var options = new AsyncApiOptions(); var schemaGenerator = new SchemaGenerator(Options.Create(options)); var documentGenerator = new DocumentGenerator(Options.Create(options), schemaGenerator); // Act var document = documentGenerator.GenerateDocument(new [] { typeof(TenantSingleMessagePublisher).GetTypeInfo() }); // Assert document.ShouldNotBeNull(); document.Channels.Count.ShouldBe(1); var channel = document.Channels.First(); channel.Key.ShouldBe("asw.tenant_service.tenants_history"); channel.Value.Description.ShouldBe("Tenant events."); var publish = channel.Value.Publish; publish.ShouldNotBeNull(); publish.OperationId.ShouldBe("TenantSingleMessagePublisher"); publish.Summary.ShouldBe("Publish single domain event about tenants."); var message = publish.Message.ShouldBeOfType <Message>(); message.Name.ShouldBe("anyTenantCreated"); }
/// <summary> /// Generates all schema classes for the specified service /// </summary> /// <param name="service"></param> /// <returns></returns> public CodeNamespace GenerateSchemaClasses(IService service) { service.ThrowIfNull("service"); logger.Debug("Starting to generate schemas for {1} in namespace {0}", schemaNamespace, service.Name); LogDecorators(); var codeNamespace = new CodeNamespace(schemaNamespace); codeNamespace.Imports.Add(new CodeNamespaceImport("System")); codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); SchemaGenerator generator = new SchemaGenerator(decorators); // Generate implementation details IDictionary <JsonSchema, SchemaImplementationDetails> implementationDetails = implementationDetailsGenerator.GenerateDetails(service); // Generate schemas foreach (var schemaPair in service.Schemas) { logger.Debug("Generating Schema {0}", schemaPair.Key); // Create schema codeNamespace.Types.Add( generator.CreateClass(schemaPair.Value, implementationDetails, service.Schemas.Keys)); } return(codeNamespace); }
/// <inheritdoc /> protected override void PostStart(IComponentContext componentContext) { base.PostStart(componentContext); var contextManager = componentContext.Resolve <UniversalContextFactory>(); var config = componentContext.Resolve <Config>(); var connectionString = config.GetString(NodeManagerActor.ConfigConnectionStringPath); var repository = componentContext.Resolve <IPackageRepository>(); var databaseName = config.GetString(NodeManagerActor.ConfigDatabaseNamePath); using (var context = contextManager.CreateContext <ConfigurationContext>("InMemory", connectionString, databaseName)) { context.ResetValueGenerators(); context.Database.EnsureDeleted(); var seeder = new Seeder(config, contextManager, repository); Serilog.Log.Information("!!!!!!!!!!! Seeding started"); seeder.Seed(); Serilog.Log.Information("!!!!!!!!!!! Seeding finished"); } var schemaProvider = componentContext.Resolve <SchemaProvider>(); var apiProviders = componentContext.Resolve <IEnumerable <API.Provider.ApiProvider> >() .Select(p => new DirectProvider(p, error => Serilog.Log.Error("API ERROR: {error}", error))) .Cast <ApiProvider>() .ToList(); schemaProvider.CurrentSchema = SchemaGenerator.Generate(apiProviders); }
public void Trivial2Test() { var api = new ApiDescription { ApiName = "TestApi1", TypeName = "TestApi1", Version = new Version("0.0.0.1"), }; var provider = new MoqProvider { Description = api }; var schema = SchemaGenerator.Generate(new List <ApiProvider> { provider }); using (var printer = new SchemaPrinter(schema)) { var description = printer.Print(); this.output.WriteLine(description); Assert.False(string.IsNullOrWhiteSpace(description)); } Assert.NotNull(schema.Query); Assert.Equal(3, schema.Query.Fields.Count()); Assert.True(schema.Query.HasField("api")); }
public void ShouldSetTitle() { var generator = new SchemaGenerator <ISampleService>(); var schema = generator.Generate(); Assert.Equal(nameof(ISampleService), schema.Title); }
private static DocumentFilterContext GetDocumentFilterContext(ApiVersionModel versionModel) { var actionDescriptor = new ActionDescriptor(); actionDescriptor.SetProperty(versionModel); var apiDescription = new ApiDescription { ActionDescriptor = actionDescriptor }; var apiDescriptions = new List <ApiDescription> { apiDescription }; var schemaGeneratorOptions = new SchemaGeneratorOptions(); var jsonSerializerOptions = new JsonSerializerOptions(); var jsonSerializerDataContractResolver = new JsonSerializerDataContractResolver(jsonSerializerOptions); var schemaGenerator = new SchemaGenerator(schemaGeneratorOptions, jsonSerializerDataContractResolver); var schemaRepository = new SchemaRepository(); return(new DocumentFilterContext(apiDescriptions, schemaGenerator, schemaRepository)); }
public Dictionary <string, object> GetMeta() { var schema = SchemaGenerator.GenerateFromType <Note>(); using var ms = new MemoryStream(); var writer = new Utf8JsonWriter(ms); var serializerOptions = new JsonSerializerOptions() { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase }; SchemaSerializer.Serialize(schema, writer, serializerOptions); writer.Flush(); ms.Position = 0; using var sr = new StreamReader(ms); var serializedSchema = sr.ReadToEnd(); return(new Dictionary <string, object> { ["schema"] = serializedSchema }); }
private void GenerateButton_Click(object sender, EventArgs e) { SelectProjectButton.Enabled = false; GenerateButton.Enabled = false; JsonSchemaParser.GenerateArraysInstedOfLists = ArrayCollectionsCheckbox.Checked; LogTextBox.Text = "Generating..."; Schema schema; try { schema = JsonSchemaParser.ComposeEndpointSchema(SchemaTextBox.Text); } catch (Exception ex) { LogTextBox.Text += "\r\nError reading endpoint"; LogTextBox.Text += "\r\n" + ex.Message; GenerateButton.Enabled = true; SelectProjectButton.Enabled = true; return; } LogTextBox.Text += "\r\nEnpoint schema - OK"; LogTextBox.Text += "\r\nWriting code..."; SchemaGenerator.WriteCSharp(directoryPath + "\\", schema, (_) => LogTextBox.Text += ("\r\n" + _), "Acumatica." + endpointName.Replace(".", "_"), pathToProject, additionalPath); }
public void BasicExample_WithEnums_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(StarWarsAttributeSchema)); var query = @" query HeroNameQuery { hero { appearsIn friends } } "; var expected = @"{ hero: { appearsIn: [ ""NEWHOPE"", ""EMPIRE"", ""JEDI"" ], friends: [""1"",""4""] } }"; GraphAssert.QuerySuccess(schema, query, expected); }
public void GetDocument_GeneratesDocumentWithMultipleMessagesPerChannel() { // Arrange var options = new AsyncApiOptions(); var schemaGenerator = new SchemaGenerator(Options.Create(options)); var documentGenerator = new DocumentGenerator(Options.Create(options), schemaGenerator); // Act var document = documentGenerator.GenerateDocument(new [] { typeof(TenantMessageConsumer).GetTypeInfo() }); // Assert document.ShouldNotBeNull(); document.Channels.Count.ShouldBe(1); var channel = document.Channels.First(); channel.Key.ShouldBe("asw.tenant_service.tenants_history"); channel.Value.Description.ShouldBe("Tenant events."); var subscribe = channel.Value.Subscribe; subscribe.ShouldNotBeNull(); subscribe.OperationId.ShouldBe("TenantMessageConsumer"); subscribe.Summary.ShouldBe("Subscribe to domains events about tenants."); var messages = subscribe.Message.ShouldBeOfType <Messages>(); messages.OneOf.Count.ShouldBe(3); messages.OneOf.ShouldContain(m => m.Name == "tenantCreated"); messages.OneOf.ShouldContain(m => m.Name == "tenantUpdated"); messages.OneOf.ShouldContain(m => m.Name == "tenantRemoved"); }
/// <summary> /// Ads a request model to the endpoint operation. /// </summary> /// <param name="endpointInfo"></param> /// <param name="requestType"></param> /// <param name="contentType"></param> /// <param name="description"></param> /// <param name="required"></param> /// <returns></returns> public static Endpoint WithRequestModel(this Endpoint endpointInfo, Type requestType, string contentType = null, string description = null, bool required = true) { if (contentType is null) { contentType = @"application/json"; } string Ref = $"#/components/schemas/{SchemaGenerator.GetOrSaveSchemaReference(requestType)}"; endpointInfo.RequestBody = new RequestBody { Required = required, Description = description, Content = new Dictionary <string, MediaTypeObject> { { contentType, new MediaTypeObject() { Schema = new SchemaRef() { Ref = Ref } } } } }; return(endpointInfo); }
public void SetRequestAdvancedString_Introspection_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(EchoStateSchema)); var query = @"{ __type(name:""Input_SetRequestAdvancedString""){ name inputFields{ name type{ kind ofType{ kind } } } } } "; var expected = @"{""__type"":{""name"":""Input_SetRequestAdvancedString"",""inputFields"":[{""name"":""nonRequiredBool"",""type"":{""kind"":""SCALAR"",""ofType"":null}},{""name"":""nonRequiredObject"",""type"":{""kind"":""INPUT_OBJECT"",""ofType"":null}},{""name"":""notRequiredString"",""type"":{""kind"":""SCALAR"",""ofType"":null}},{""name"":""nullRequiredDateTime"",""type"":{""kind"":""SCALAR"",""ofType"":null}},{""name"":""requiredObject"",""type"":{""kind"":""INPUT_OBJECT"",""ofType"":null}},{""name"":""requiredObjects"",""type"":{""kind"":""LIST"",""ofType"":{""kind"":""INPUT_OBJECT""}}},{""name"":""requiredString"",""type"":{""kind"":""SCALAR"",""ofType"":null}}]}}"; GraphAssert.QuerySuccess(schema, query, expected); }
public SchemaGenerationTests() { _schemaRepository = new SchemaRepository(); var options = new AsyncApiOptions(); _schemaGenerator = new SchemaGenerator(Options.Create(options)); }
public void SetAdvanced_WithNullableParam_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(EchoStateSchema)); var query = @" mutation SetState($dec:Decimal!, $int:Int!, $int2:Int!, $date1:Date!, $str:String){ set:setAdvanced(request:{decimal:$dec, data:$int, nonRequiredInt:$int2, nullRequiredDateTime:$date1, notRequiredString:$str}){ decimal data state } } "; var expected = @"{ set: { decimal:24.15, data: 3, state: ""Open"" } }"; GraphAssert.QuerySuccess(schema, query, expected, "{dec:24.15, int:2, int2:1, date1:\"1-1-2011\"}"); }
static void Main(string[] args) { var generator = new SchemaGenerator(); // optional controls on here, we can add more add needed var schema = generator.GetSchema <IConferencesService>(); // there is also a non-generic overload that takes Type Console.WriteLine("SCHEMA: " + schema); }
static void Main(string[] args) { var generator = new SchemaGenerator(); var schema = generator.GetSchema <IConferencesService>(); Console.WriteLine("***ProtoBuf Schema***: \n\n" + schema); }
public void BasicClassInputExample_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(GenericsSchema)); var query = @" { echoClassGenerics{ list{innerInt} } echoClassGenerics2{ list{inner2Int} } } "; var expected = @"{ echoClassGenerics: { list: [{innerInt:1}] }, echoClassGenerics2: { list: [{inner2Int:2}] } }"; GraphAssert.QuerySuccess(schema, query, expected); }
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 List <WeekDayViewModel> GenerateSchema(List <RandomizeActivitySummeriesViewModel> randomizeActivitySummeriesViewModel, string userId) { //change null to right userId SchemaGenerator schemaGenerator = new SchemaGenerator(GetWeekDayViewModelsForPartial(null), GetWeekDayViewModels(userId)); return(schemaGenerator.GenerateSchema(randomizeActivitySummeriesViewModel, userId)); }
public void GetTimeSpanAsVariable_IsSafe() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(DateSchema)); var query = @" query($ts:TimeSpan!) { dates(dates:{timeSpan:$ts}) { timeSpan } } "; var variables = @"{ ts:""1.23:59:59"" }"; var expected = @"{ dates: { timeSpan:""1.23:59:59"" } }"; GraphAssert.QuerySuccess(schema, query, expected, variables); }
public async Task Methods_Perform_Async() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(PerformanceSchema)); var query = @"{ slow1:slowCall{ date } slow2:slowCall{ date } slow3:slowCall{ date } }"; var stopwatch = new Stopwatch(); stopwatch.Start(); var result = await DocumentOperations.ExecuteOperationsAsync(schema, null, query, validate : false); stopwatch.Stop(); Assert.IsTrue(stopwatch.Elapsed.TotalSeconds < 2); Assert.IsNull(result.Errors); }
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 void ShouldSetNameWhenAttribute() { var generator = new SchemaGenerator <ISampleService>(); var schema = generator.Generate(); Assert.Equal(typeof(ISampleService).GetTypeInfo().GetCustomAttribute <ServiceAttribute>().Name, schema.Name); }
/// <summary> /// Ads a request parameters to the endpoint operation. /// </summary> /// <param name="endpointInfo"></param> /// <param name="name"></param> /// <param name="type"></param> /// <param name="format"></param> /// <param name="required"></param> /// <param name="description"></param> /// <param name="loc"></param> /// <param name="deprecated"></param> /// <returns></returns> public static Endpoint WithRequestParameter(this Endpoint endpointInfo, string name, Type type = null, string format = null, bool required = true, string description = null, string loc = "path", bool deprecated = false) { if (endpointInfo.RequestParameters is null) { endpointInfo.RequestParameters = new List <RequestParameter>(); } if (type is null) { type = typeof(string); } var schema = SchemaGenerator.GetSchemaByType(type); endpointInfo.RequestParameters.Add(new RequestParameter { Required = required, Description = description, In = loc, Name = name, Deprecated = deprecated, Schema = schema }); return(endpointInfo); }
private void button2_Click(object sender, EventArgs e) { button1.Enabled = false; button2.Enabled = false; textBox2.Text = "Generating..."; Schema schema; try { schema = JsonSchemaParser.ComposeEndpointSchema(textBox1.Text); } catch (Exception ex) { textBox2.Text += "\r\nError reading endpoint"; textBox2.Text += "\r\n" + ex.Message; button1.Enabled = true; button2.Enabled = true; return; } textBox2.Text += "\r\nEnpoint schema - OK"; textBox2.Text += "\r\nWriting code..."; SchemaGenerator.WriteCSharp(directoryPath + "\\", schema, (_) => textBox2.Text += ("\r\n" + _), "Acumatica." + endpointName.Replace(".", "_"), pathToProject, additionalPath); }
public void BasicExample_WithQueryAndMutation_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(EchoStateSchema)); var query = @" mutation SetState{ setState (request:Open){ state } } query GetState{ getState{ state } } "; var expected = @"{ SetState:{setState: { state: ""Open"" }}, GetState:{getState: { state: ""Open"" } }}"; GraphAssert.QueryOperationsSuccess(schema, query, expected); }
static void Main(string[] args) { while (true) { var gen = new SchemaGenerator(new List <string> { @"C:\Users\toshe\source\repos\Test\Test\bin\Test.dll" }); var schema = gen.Generate(url: "http://*****:*****@"C:\Users\toshe\Desktop\Test.schema"); var endpoint = schema.Controllers[0].Endpoints[0]; System.Console.WriteLine(JsonConvert.SerializeObject(schema, Formatting.Indented)); System.Console.WriteLine("============================"); System.Console.WriteLine(schema.Do(endpoint)); System.Console.WriteLine("============================"); System.Console.WriteLine(Request.Do(schema, schema.Controllers[0].Endpoints[1], Input.Get(schema.Controllers[0].Endpoints[1].Input))); System.Console.WriteLine("============================"); System.Console.WriteLine(schema.Do(schema.Controllers[0].Endpoints[2])); System.Console.ReadKey(); } }
public void CreateSchema_WithClassArgument_HasExpectedSchema() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(AsyncSchema)); var sut = schema.AllTypes; Assert.IsTrue(sut.Any(t => t.Name == "Input_Schema1Request")); }
public OpenApiSchema GenerateSchema(Type type, SchemaRepository schemaRepository, MemberInfo memberInfo = null, ParameterInfo parameterInfo = null) { var serializerType = type.GetCustomAttribute <JsonRpcTypeInfoAttribute>()?.SerializerType; var resolver = GetResolver(serializerType); var generator = new SchemaGenerator(generatorOptions, resolver); return(generator.GenerateSchema(type, schemaRepository, memberInfo, parameterInfo)); }