/// <summary>Generates the property name.</summary> /// <param name="property">The property.</param> /// <returns>The new name.</returns> public virtual string Generate(JsonProperty property) { return(ConversionUtilities.ConvertToUpperCamelCase(property.Name .Replace("@", "") .Replace(".", "-"), true) .Replace("-", "_")); }
public static (bool isSinlgeClient, string typeName) GenerateCSharp(SwaggerDocument document, ApiClientDefinition definition) { var nameGenerator = new CustomNameGenerator(); var settings = new SwaggerToCSharpClientGeneratorSettings() { GenerateSyncMethods = true, OperationNameGenerator = nameGenerator, GenerateOptionalParameters = true, }; settings.CSharpGeneratorSettings.ClassStyle = CSharpClassStyle.Poco; settings.CSharpGeneratorSettings.Namespace = definition.Namespace; settings.CSharpGeneratorSettings.ArrayType = "System.Collections.Generic.List"; settings.CSharpGeneratorSettings.PropertyNameGenerator = new MyPropertyNameGenerator(c => ConversionUtilities.ConvertToUpperCamelCase(c, true)); var generator = new SwaggerToCSharpClientGenerator(document, settings); var csharp = generator.GenerateFile(); var newClient = InjectWrapperClass(csharp, Path.GetFileNameWithoutExtension(definition.CSharpClient), document, settings.OperationNameGenerator, out var isSinlgeClient, out var wrapperTypeName); definition.IsSingleClient = isSinlgeClient; if (definition.GenerateWrapperClass) { csharp = newClient; } File.WriteAllText(definition.CSharpClient, csharp); return(isSinlgeClient, wrapperTypeName); }
private static string InjectWrapperClass(string csharpCode, string className, SwaggerDocument document, IOperationNameGenerator nameGenerator, out bool isSinlgeClient, out string clientName) { var clients = document.Operations.Select(o => nameGenerator.GetClientName(document, o.Path, o.Method, o.Operation)).Distinct().ToArray(); if (clients.Length == 1) { isSinlgeClient = true; clientName = clients[0] + "Client"; return(csharpCode); } else { isSinlgeClient = false; clientName = className; var properties = from c in clients let name = ConversionUtilities.ConvertToUpperCamelCase(c, true) let type = name + "Client" select $"public {type} {(string.IsNullOrEmpty(name) ? "Root" : name)} {{ get; set; }}"; var wrapperClass = $@" public class {className} {{ {ConversionUtilities.Tab(string.Join("\n", properties), 1)} }}".Replace("\r\n", "\n"); var namespaceClosing = csharpCode.LastIndexOf('}'); return(csharpCode.Insert(namespaceClosing, ConversionUtilities.Tab(wrapperClass, 1) + "\n")); } }
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { return(ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-"), true) .Replace(".", "_") .Replace("#", "_")); }
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema.Enumeration" /> and <see cref="JsonSchema.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema schema) { if (string.IsNullOrEmpty(name)) { return("Empty"); } if (name.StartsWith("_-")) { name = "__" + name.Substring(2); } return(ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace(".", "_") .Replace(",", "_") .Replace("#", "_") .Replace("&", "_") .Replace("-", "_") .Replace("'", "_") .Replace("(", "_") .Replace(")", "_") .Replace("+", "_") .Replace("\\", "_")); }
private string GetClrItemName(string schemaItemTitle) { if (string.IsNullOrEmpty(schemaItemTitle) || schemaItemTitle == "(no title)") { return("NoTitle"); } return(ConversionUtilities.ConvertToUpperCamelCase(schemaItemTitle, true)); }
internal PropertyModel(JsonProperty property, CSharpTypeResolver resolver, CSharpGeneratorSettings settings) : base(property, new DefaultValueGenerator(resolver), settings) { _property = property; _settings = settings; _resolver = resolver; PropertyName = ConversionUtilities.ConvertToUpperCamelCase(GetGeneratedPropertyName(), true); }
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema.Enumeration" /> and <see cref="JsonSchema.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema schema) { if (string.IsNullOrEmpty(name)) { return("Empty"); } switch (name) { case "=": name = "Eq"; break; case "!=": name = "Ne"; break; case ">": name = "Gt"; break; case "<": name = "Lt"; break; case ">=": name = "Ge"; break; case "<=": name = "Le"; break; case "~=": name = "Approx"; break; } if (name.StartsWith("-")) { name = "Minus" + name.Substring(1); } if (name.StartsWith("+")) { name = "Plus" + name.Substring(1); } if (name.StartsWith("_-")) { name = "__" + name.Substring(2); } return(InvalidNameCharactersPattern.Replace(ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @"").Replace('_', '-'), true), "_")); }
/// <summary>Generates the type name for the given schema.</summary> /// <param name="schema">The schema.</param> /// <param name="typeNameHint">The type name hint.</param> /// <returns>The type name.</returns> protected override string Generate(JsonSchema schema, string typeNameHint) { if (string.IsNullOrEmpty(typeNameHint) && schema.HasTypeNameTitle) { typeNameHint = schema.Title; } var input = typeNameHint?.Split('.').Last() ?? "Anonymous"; return(ConversionUtilities.ConvertToUpperCamelCase(input.Replace('_', '-'), true)); }
private string GetOperationName(SwaggerOperation operation) { var segments = operation.OperationId.Split('_').ToArray(); if (segments.Length >= 2) { segments = segments.Skip(1).ToArray(); } return(segments.Length > 0 ? ConversionUtilities.ConvertToUpperCamelCase(string.Join("-", segments), true) : "Index"); }
internal PropertyModel(JsonProperty property, CSharpTypeResolver resolver, CSharpGeneratorSettings settings) : base(property) { Name = property.Name; HasDescription = !string.IsNullOrEmpty(property.Description); Description = ConversionUtilities.RemoveLineBreaks(property.Description); PropertyName = ConversionUtilities.ConvertToUpperCamelCase(property.Name); FieldName = ConversionUtilities.ConvertToLowerCamelCase(property.Name); Required = property.IsRequired && settings.RequiredPropertiesMustBeDefined ? "Required.Always" : "Required.Default"; IsStringEnum = property.ActualPropertySchema.IsEnumeration && property.ActualPropertySchema.Type == JsonObjectType.String; Type = resolver.Resolve(property.ActualPropertySchema, property.IsNullable, property.Name); }
/// <summary>Generates the property name.</summary> /// <param name="property">The property.</param> /// <returns>The new name.</returns> public virtual string Generate(JsonProperty property) { return(ConversionUtilities.ConvertToUpperCamelCase(property.Name .Replace("\"", string.Empty) .Replace("@", string.Empty) .Replace(".", "-") .Replace("=", "-") .Replace("+", "plus"), true) .Replace("*", "Star") .Replace(":", "_") .Replace("-", "_")); }
public static (bool isSingleClient, string typeName) GenerateCSharp(SwaggerDocument document, ApiClientDefinition definition, bool promptOnFileOverwrite) { var className = Path.GetFileNameWithoutExtension(definition.CSharpClient); var settings = new SwaggerToCSharpClientGeneratorSettings() { GenerateSyncMethods = true, OperationNameGenerator = new CustomOperationNameGenerator(), GenerateOptionalParameters = true, CSharpGeneratorSettings = { ClassStyle = CSharpClassStyle.Poco, Namespace = definition.Namespace, ArrayType = "System.Collections.Generic.List", PropertyNameGenerator = new CustomPropertyNameGenerator(c => ConversionUtilities.ConvertToUpperCamelCase(c,true)), } }; // detect whether there will be multiple clients or just one var clientNames = document.Operations .Select(o => settings.OperationNameGenerator.GetClientName(document, o.Path, o.Method, o.Operation)) .Distinct() .ToArray(); definition.IsSingleClient = clientNames.Length == 1; if (definition.IsSingleClient) { // set the class name only when Swagger generates one client, otherwise all classes would have the same name settings.ClassName = className; } settings.CSharpGeneratorSettings.TypeNameGenerator = new DotvmmCSharpTypeNameGenerator(settings.CSharpGeneratorSettings, document); settings.CSharpGeneratorSettings.TemplateFactory = new DotvvmClientTemplateFactory(settings.CodeGeneratorSettings, new[] { typeof(CSharpGeneratorSettings).Assembly, typeof(SwaggerToCSharpGeneratorSettings).Assembly }); var resolver = SwaggerToCSharpTypeResolver.CreateWithDefinitions(settings.CSharpGeneratorSettings, document); var generator = new DotvvmSwaggerToCSharpClientGenerator(document, settings, resolver); var csharp = generator.GenerateFile(); if (definition.GenerateWrapperClass && !definition.IsSingleClient) { csharp = ApiClientUtils.InjectWrapperClass(csharp, className, clientNames); } FileSystemHelpers.WriteFile(definition.CSharpClient, csharp, promptOnFileOverwrite); return(definition.IsSingleClient, className); }
/// <summary>Generates the type name for the given schema.</summary> /// <param name="schema">The schema.</param> /// <param name="typeNameHint">The type name hint.</param> /// <returns>The type name.</returns> protected virtual string Generate(JsonSchema4 schema, string typeNameHint) { if (string.IsNullOrEmpty(typeNameHint) && string.IsNullOrEmpty(schema.Title) == false && Regex.IsMatch(schema.Title, "^[a-zA-Z0-9_]*$")) { typeNameHint = schema.Title; } var lastSegment = typeNameHint?.Split('.').Last(); return(ConversionUtilities.ConvertToUpperCamelCase(lastSegment ?? "Anonymous", true)); }
private void GenerateObject(JToken token, JsonSchema4 schema, JsonSchema4 rootSchema) { schema.Type = JsonObjectType.Object; foreach (var property in ((JObject)token).Properties()) { var propertySchema = new JsonProperty(); var propertyName = property.Value.Type == JTokenType.Array ? ConversionUtilities.Singularize(property.Name) : property.Name; var typeNameHint = ConversionUtilities.ConvertToUpperCamelCase(propertyName, true); Generate(property.Value, propertySchema, rootSchema, typeNameHint); schema.Properties[property.Name] = propertySchema; } }
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary> /// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param> /// <param name="name">The name/key.</param> /// <param name="value">The value.</param> /// <param name="schema">The schema.</param> /// <returns>The enumeration name.</returns> public string Generate(int index, string name, object value, JsonSchema4 schema) { if (name.StartsWith("_-")) { name = "__" + name.Substring(2); } return(ConversionUtilities.ConvertToUpperCamelCase(name .Replace(":", "-").Replace(@"""", @""), true) .Replace(".", "_") .Replace("#", "_") .Replace("-", "_") .Replace("\\", "_")); }
public static string InjectWrapperClass(string csharpCode, string className, string[] clientNames) { var properties = from c in clientNames let name = ConversionUtilities.ConvertToUpperCamelCase(c, true) let type = name + "Client" select $"public {type} {(string.IsNullOrEmpty(name) ? "Root" : name)} {{ get; set; }}"; var wrapperClass = $@" public class {className} {{ {ConversionUtilities.Tab(string.Join("\n", properties), 1)} }}".Replace("\r\n", "\n"); var namespaceClosing = csharpCode.LastIndexOf('}'); return(csharpCode.Insert(namespaceClosing, ConversionUtilities.Tab(wrapperClass, 1) + "\n")); }
/// <summary>Gets the type name hint for the property.</summary> protected string GetTypeNameHint() { var propertyName = PropertyName; if (_property.IsEnumeration == false) return propertyName; var className = _classTemplateModel.ClassName; if (className.Contains("Anonymous")) return propertyName; if (propertyName.StartsWith(className, StringComparison.OrdinalIgnoreCase)) return propertyName; return className + ConversionUtilities.ConvertToUpperCamelCase(PropertyName, false); }
/// <summary>Resolves the type of the parameter.</summary> /// <param name="parameter">The parameter.</param> /// <returns>The parameter type name.</returns> protected virtual string ResolveParameterType(SwaggerParameter parameter) { var schema = parameter.ActualSchema; if (parameter.CollectionFormat == SwaggerParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array)) { schema = new JsonSchema4 { Type = JsonObjectType.Array, Item = schema } } ; var typeNameHint = ConversionUtilities.ConvertToUpperCamelCase(parameter.Name, true); return(Resolver.Resolve(schema, parameter.IsRequired == false || parameter.IsNullable(BaseSettings.CodeGeneratorSettings.NullHandling), typeNameHint)); }
private List <EnumerationEntry> GetEnumeration(JsonSchema4 schema) { var entries = new List <EnumerationEntry>(); for (int i = 0; i < schema.Enumeration.Count; i++) { var value = schema.Enumeration.ElementAt(i); var name = schema.EnumerationNames.Count > i? schema.EnumerationNames.ElementAt(i) : schema.Type == JsonObjectType.Integer ? "_" + value : value.ToString(); entries.Add(new EnumerationEntry { Value = schema.Type == JsonObjectType.Integer ? value.ToString() : "<any>\"" + value + "\"", Name = ConversionUtilities.ConvertToUpperCamelCase(name, true) }); } return(entries); }
public void CanResolveTypesForSourceAndTarget() { var tg = new JsonTypeGenerator(); var source = tg.Generate(File.ReadAllText(TestFiles.Person), TestFiles.Person, "Foo.Bar"); var target = tg.Generate(File.ReadAllText(TestFiles.PersonBasic), TestFiles.PersonBasic, "Baz"); Write(source.Code); Write(target.Code); var mapping = JsonConvert.DeserializeObject <Mapping>(File.ReadAllText(TestFiles.PersonMapping)); mapping.RebuildRelationships(); var mappings = new Dictionary <int, TypeMapping>(); var sourceItem = mapping.SourceInfo.Roots[0]; var targetItem = mapping.TargetInfo.Roots[0]; var sourcetype = source.Assembly.DefinedTypes.First(a => a.Name == ConversionUtilities.ConvertToUpperCamelCase(sourceItem.title, true)); var targettype = target.Assembly.DefinedTypes.First(a => a.Name == ConversionUtilities.ConvertToUpperCamelCase(targetItem.title, true)); var resolver = new TypeResolver(); resolver.Resolve(mappings, sourcetype, targettype, sourceItem, targetItem, mapping); Assert.Equal(4, mappings.Keys.Count); foreach (var tm in mappings.Values) { foreach (var schemaItemMapping in tm.Mappings) { Write(string.Format("Item {0} of type {1} will be mapped from {2}", schemaItemMapping.TargetSchemaItem.title, tm.TargetProperty, schemaItemMapping.SourceProperty)); } } var tm1 = mappings[targetItem.children.First(a => a.title == "firstName").key]; Assert.Equal(typeof(System.String), tm1.Mappings[0].SourceProperty.PropertyType); Assert.NotNull(tm1.Mappings[0].SourcePath); var tm2 = mappings[targetItem.children.First(a => a.title == "lastName").key]; Assert.Equal(typeof(System.String), tm2.Mappings[0].SourceProperty.PropertyType); Assert.NotNull(tm2.Mappings[0].SourcePath); }
/// <summary>Gets the operation name for a given operation.</summary> /// <param name="document">The Swagger document.</param> /// <param name="path">The HTTP path.</param> /// <param name="httpMethod">The HTTP method.</param> /// <param name="operation">The operation.</param> /// <returns>The operation name.</returns> public virtual string GetOperationName(OpenApiDocument document, string path, string httpMethod, OpenApiOperation operation) { var operationName = ConvertPathToName(path); var hasNameConflict = document.Paths .SelectMany(pair => pair.Value.Select(p => new { Path = pair.Key.Trim('/'), HttpMethod = p.Key, Operation = p.Value })) .Where(op => GetClientName(document, op.Path, op.HttpMethod, op.Operation) == GetClientName(document, path, httpMethod, operation) && ConvertPathToName(op.Path) == operationName ).ToList() .Count > 1; if (hasNameConflict) { operationName += ConversionUtilities.ConvertToUpperCamelCase(httpMethod, false); } return(operationName); }
internal override string RenderClientCode(string controllerName, IEnumerable <OperationModel> operations) { var hasClientBaseClass = !string.IsNullOrEmpty(Settings.ControllerBaseClass); var template = new WebApiControllerTemplate(); template.Initialize(new { Class = Settings.ClassName.Replace("{controller}", ConversionUtilities.ConvertToUpperCamelCase(controllerName)), BaseClass = Settings.ControllerBaseClass, HasBaseClass = hasClientBaseClass, BaseUrl = _service.BaseUrl, HasOperations = operations.Any(), Operations = operations }); return(template.Render()); }
public static (bool isSingleClient, string typeName) GenerateCSharp(SwaggerDocument document, ApiClientDefinition definition) { var settings = new SwaggerToCSharpClientGeneratorSettings() { GenerateSyncMethods = true, OperationNameGenerator = new CustomOperationNameGenerator(), GenerateOptionalParameters = true, CSharpGeneratorSettings = { ClassStyle = CSharpClassStyle.Poco, Namespace = definition.Namespace, ArrayType = "System.Collections.Generic.List", PropertyNameGenerator = new CustomPropertyNameGenerator(c => ConversionUtilities.ConvertToUpperCamelCase(c,true)), } }; settings.CSharpGeneratorSettings.TypeNameGenerator = new DotvmmCSharpTypeNameGenerator(settings.CSharpGeneratorSettings, document); settings.CSharpGeneratorSettings.TemplateFactory = new DotvvmClientTemplateFactory(settings.CodeGeneratorSettings, new[] { typeof(CSharpGeneratorSettings).Assembly, typeof(SwaggerToCSharpGeneratorSettings).Assembly }); var resolver = SwaggerToCSharpTypeResolver.CreateWithDefinitions(settings.CSharpGeneratorSettings, document); var generator = new DotvvmSwaggerToCSharpClientGenerator(document, settings, resolver); var csharp = generator.GenerateFile(); var newClient = ApiClientUtils.InjectWrapperClass(csharp, Path.GetFileNameWithoutExtension(definition.CSharpClient), document, settings.OperationNameGenerator, out var isSingleClient, out var wrapperTypeName); definition.IsSingleClient = isSingleClient; if (definition.GenerateWrapperClass) { csharp = newClient; } File.WriteAllText(definition.CSharpClient, csharp); return(isSingleClient, wrapperTypeName); }
/// <summary>Resolves the type of the parameter.</summary> /// <param name="parameter">The parameter.</param> /// <returns>The parameter type name.</returns> protected virtual string ResolveParameterType(OpenApiParameter parameter) { var schema = parameter.ActualSchema; if (parameter.IsXmlBodyParameter) { return("string"); } if (parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi && !schema.Type.HasFlag(JsonObjectType.Array)) { schema = new JsonSchema { Type = JsonObjectType.Array, Item = schema }; } var typeNameHint = !schema.HasTypeNameTitle ? ConversionUtilities.ConvertToUpperCamelCase(parameter.Name, true) : null; var isNullable = parameter.IsRequired == false || parameter.IsNullable(_settings.CodeGeneratorSettings.SchemaType); return(_resolver.Resolve(schema, isNullable, typeNameHint)); }
private string GenerateInternal(JsonSchema4 schema) { if (!string.IsNullOrEmpty(schema.TypeNameRaw)) { return(ConversionUtilities.ConvertToUpperCamelCase(schema.TypeNameRaw, true)); } if (schema.ExtensionData != null && schema.ExtensionData.Any() && schema.ExtensionData.ContainsKey("typeName")) { return(ConversionUtilities.ConvertToUpperCamelCase(schema.ExtensionData["typeName"].ToString(), true)); } if (!string.IsNullOrEmpty(schema.Title)) { return(ConversionUtilities.ConvertToUpperCamelCase(schema.Title, true)); } if (schema.ParentSchema == null) { return(defaultRootName); } return(null); }
internal override string RenderClientCode(string controllerName, IEnumerable <OperationModel> operations) { GenerateDataConversionCodes(operations); var template = Settings.CreateTemplate(); template.Initialize(new { Class = Settings.ClassName.Replace("{controller}", ConversionUtilities.ConvertToUpperCamelCase(controllerName)), HasOperations = operations.Any(), Operations = operations, UsesKnockout = Settings.TypeScriptGeneratorSettings.TypeStyle == TypeScriptTypeStyle.KnockoutClass, GenerateClientInterfaces = Settings.GenerateClientInterfaces, BaseUrl = _service.BaseUrl, UseDtoClasses = Settings.TypeScriptGeneratorSettings.TypeStyle != TypeScriptTypeStyle.Interface, PromiseType = Settings.PromiseType == PromiseType.Promise ? "Promise" : "Q.Promise", PromiseConstructor = Settings.PromiseType == PromiseType.Promise ? "new Promise" : "Q.Promise" }); return(template.Render()); }
public string Generate(JsonSchema4 schema) { return("MyCustomType" + ConversionUtilities.ConvertToUpperCamelCase(schema.TypeNameRaw)); }
public string Generate(JsonProperty property) { return("MyCustom" + ConversionUtilities.ConvertToUpperCamelCase(property.Name)); }
/// <summary>Generates the name of the controller based on the provided settings.</summary> /// <param name="controllerName">Name of the controller.</param> /// <returns>The controller name.</returns> public string GenerateControllerName(string controllerName) { return(ClassName.Replace("{controller}", ConversionUtilities.ConvertToUpperCamelCase(controllerName, false))); }