/// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient">The service client.</param> private void ApplyPagination(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException(nameof(serviceClient)); } foreach (Method method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { string nextLinkName = null; var ext = method.Extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer; if (ext == null) { continue; } nextLinkName = CodeNamer.GetPropertyName((string)ext["nextLinkName"]); string itemName = CodeNamer.GetPropertyName((string)ext["itemName"] ?? "value"); foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray()) { CompositeType compositeType = (CompositeType)method.Responses[responseStatus].Body; SequenceType sequenceType = compositeType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if (sequenceType != null) { compositeType.Extensions[AzureExtensions.PageableExtension] = true; PageTemplateModel pageTemplateModel = new PageTemplateModel(compositeType, serviceClient.ModelTypes, nextLinkName, itemName); if (!pageModels.Contains(pageTemplateModel)) { pageModels.Add(pageTemplateModel); } } } } }
/// <summary> /// Normalizes client model using Azure-specific extensions. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> /// <param name="codeNamer">AutoRest settings</param> /// <returns></returns> public static void NormalizeAzureClientModel(ServiceClient serviceClient, Settings settings, CodeNamer codeNamer) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } settings.AddCredentials = true; // This extension from general extensions must be run prior to Azure specific extensions. ProcessParameterizedHost(serviceClient, settings); UpdateHeadMethods(serviceClient); ParseODataExtension(serviceClient); FlattenModels(serviceClient); FlattenMethodParameters(serviceClient, settings); AddParameterGroups(serviceClient); AddLongRunningOperations(serviceClient); AddAzureProperties(serviceClient); SetDefaultResponses(serviceClient); AddPageableMethod(serviceClient, codeNamer); }
/// <summary> /// Normalizes client model by updating names and types to be language specific. /// </summary> /// <param name="serviceClientModel"></param> public override void NormalizeClientModel(ServiceClient serviceClientModel) { PopulateAdditionalProperties(serviceClientModel); CodeNamer.NormalizeClientModel(serviceClientModel); CodeNamer.ResolveNameCollisions(serviceClientModel, Settings.Namespace, Settings.Namespace + "::Models"); }
/// <summary> /// Normalizes client model using Azure-specific extensions. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> /// <param name="codeNamer">AutoRest settings</param> /// <returns></returns> public static void NormalizeAzureClientModel(ServiceClient serviceClient, Settings settings, CodeNamer codeNamer) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } settings.AddCredentials = true; UpdateHeadMethods(serviceClient); ParseODataExtension(serviceClient); FlattenResourceProperties(serviceClient); FlattenRequestPayload(serviceClient, settings); AddLongRunningOperations(serviceClient); AddAzureProperties(serviceClient); SetDefaultResponses(serviceClient); AddParameterGroups(serviceClient); AddPageableMethod(serviceClient, codeNamer); }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } if (defaultValue != null) { if (type == PrimaryType.String) { return(CodeNamer.QuoteValue(defaultValue)); } else if (type == PrimaryType.Boolean) { return(defaultValue); } else { if (type == PrimaryType.Date || type == PrimaryType.DateTime || type == PrimaryType.DateTimeRfc1123 || type == PrimaryType.TimeSpan) { return("isodate.parse_date(\"" + defaultValue + "\")"); } if (type == PrimaryType.ByteArray) { return("bytearray(\"" + defaultValue + "\", encoding=\"utf-8\")"); } } } return(defaultValue); }
private static string GetMapping(ParameterMapping mapping, bool filterRequired = false) { string inputPath = mapping.InputParameter.Name; if (mapping.InputParameterProperty != null) { inputPath += "." + CodeNamer.CamelCase(mapping.InputParameterProperty) + "()"; } if (filterRequired && !mapping.InputParameter.IsRequired) { inputPath = "null"; } string outputPath = ""; if (mapping.OutputParameterProperty != null) { outputPath += ".with" + CodeNamer.PascalCase(mapping.OutputParameterProperty); return(string.Format(CultureInfo.InvariantCulture, "{0}({1})", outputPath, inputPath)); } else { return(string.Format(CultureInfo.InvariantCulture, "{0} = {1}", outputPath, inputPath)); } }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } if (defaultValue != null) { if (type == PrimaryType.String) { return(CodeNamer.QuoteValue(defaultValue, quoteChar: "'")); } else if (type == PrimaryType.Boolean) { return(defaultValue.ToLowerInvariant()); } else { if (type == PrimaryType.Date || type == PrimaryType.DateTime || type == PrimaryType.DateTimeRfc1123 || type == PrimaryType.TimeSpan) { return("Date.parse('" + defaultValue + "')"); } if (type == PrimaryType.ByteArray) { return("'" + defaultValue + "'.bytes.to_a"); } } } return(defaultValue); }
/// <summary> /// Normalizes client model by updating names and types to be language specific. /// </summary> /// <param name="serviceClient"></param> public override void NormalizeClientModel(ServiceClient serviceClient) { Extensions.ProcessParameterizedHost(serviceClient, Settings); PopulateAdditionalProperties(serviceClient); CodeNamer.NormalizeClientModel(serviceClient); CodeNamer.ResolveNameCollisions(serviceClient, Settings.Namespace, Settings.Namespace + "::Models"); }
private Plugin(IGeneratorSettings generatorSettings, ITransformer <TCodeModel> transformer, CodeGenerator generator, CodeNamer namer) { _generatorSettings = generatorSettings; _transformer = transformer; _generator = generator; _namer = namer; // apply custom settings to the GeneratorSettings }
private Plugin(IGeneratorSettings generatorSettings, IModelSerializer <TCodeModel> serializer, ITransformer <TCodeModel> transformer, CodeGenerator generator, CodeNamer namer) { _generatorSettings = generatorSettings; _serializer = serializer; _transformer = transformer; _generator = generator; _namer = namer; // apply custom settings to the GeneratorSettings Core.Settings.PopulateSettings(_generatorSettings, Core.Settings.Instance.CustomSettings); }
/// <summary> /// Flattens the Resource Properties. /// </summary> /// <param name="serviceClient"></param> public static void FlattenResourceProperties(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } HashSet <string> typesToDelete = new HashSet <string>(); foreach (var compositeType in serviceClient.ModelTypes.ToArray()) { if (IsAzureResource(compositeType)) { CheckAzureResourceProperties(compositeType); // First find "properties" property var propertiesProperty = compositeType.ComposedProperties.FirstOrDefault( p => p.Name.Equals(ResourceProperties, StringComparison.OrdinalIgnoreCase)); // Sub resource does not need to have properties if (propertiesProperty != null) { var propertiesModel = propertiesProperty.Type as CompositeType; // Recursively parsing the "properties" object hierarchy while (propertiesModel != null) { foreach (Property originalProperty in propertiesModel.Properties) { var pp = (Property)originalProperty.Clone(); if ( ResourcePropertyNames.Any( rp => rp.Equals(pp.Name, StringComparison.OrdinalIgnoreCase))) { pp.Name = compositeType.Name + CodeNamer.PascalCase(pp.Name); } pp.SerializedName = "properties." + pp.SerializedName; compositeType.Properties.Add(pp); } compositeType.Properties.Remove(propertiesProperty); if (!typesToDelete.Contains(propertiesModel.Name)) { typesToDelete.Add(propertiesModel.Name); } propertiesModel = propertiesModel.BaseModelType; } } } } AzureExtensions.RemoveUnreferencedTypes(serviceClient, typesToDelete); }
private static string CreateSignature(IEnumerable <ConstructorParameterModel> parameters) { var declarations = new List <string>(); foreach (var property in parameters.Select(p => p.UnderlyingProperty)) { string format = (property.IsRequired ? "{0} {1}" : "{0} {1} = default({0})"); declarations.Add(string.Format(CultureInfo.InvariantCulture, format, property.Type, CodeNamer.CamelCase(property.Name))); } return(string.Join(", ", declarations)); }
public TfProviderField LocateOrAdd(IEnumerable <string> paths) { var name = paths.FirstOrDefault(); if (name == null) { return(this); } name = CodeNamer.GetAzureRmSchemaName(name); if (!subFields.TryGetValue(name, out var field)) { field = AddField(name); } return(field.LocateOrAdd(paths.Skip(1))); }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } var primaryType = type as PrimaryType; if (defaultValue != null && primaryType != null) { if (primaryType.Type == KnownPrimaryType.String) { return(CodeNamer.QuoteValue(defaultValue)); } else if (primaryType.Type == KnownPrimaryType.Boolean) { return(defaultValue.ToLowerInvariant()); } else if (primaryType.Type == KnownPrimaryType.Long) { return(defaultValue + "L"); } else { if (primaryType.Type == KnownPrimaryType.Date) { return("LocalDate.parse(\"" + defaultValue + "\")"); } else if (primaryType.Type == KnownPrimaryType.DateTime || primaryType.Type == KnownPrimaryType.DateTimeRfc1123) { return("DateTime.parse(\"" + defaultValue + "\")"); } else if (primaryType.Type == KnownPrimaryType.TimeSpan) { return("Period.parse(\"" + defaultValue + "\")"); } else if (primaryType.Type == KnownPrimaryType.ByteArray) { return("\"" + defaultValue + "\".getBytes()"); } } } return(defaultValue); }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } PrimaryType primaryType = type as PrimaryType; if (defaultValue != null) { if (type is CompositeType) { return("new " + type.Name + "()"); } else if (primaryType != null) { if (primaryType.Type == KnownPrimaryType.String) { return(CodeNamer.QuoteValue(defaultValue)); } else if (primaryType.Type == KnownPrimaryType.Boolean) { return(defaultValue.ToLowerInvariant()); } else { if (primaryType.Type == KnownPrimaryType.Date || primaryType.Type == KnownPrimaryType.DateTime || primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || primaryType.Type == KnownPrimaryType.TimeSpan || primaryType.Type == KnownPrimaryType.ByteArray || primaryType.Type == KnownPrimaryType.Base64Url || primaryType.Type == KnownPrimaryType.UnixTime) { return("Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<" + primaryType.Name.TrimEnd('?') + ">(" + CodeNamer.QuoteValue("\"" + defaultValue + "\"") + ", this.Client.SerializationSettings)"); } } } } return(defaultValue); }
private static string GetMapping(ParameterMapping mapping) { string inputPath = mapping.InputParameter.Name; if (mapping.InputParameterProperty != null) { inputPath += ".get" + CodeNamer.PascalCase(mapping.InputParameterProperty) + "()"; } string outputPath = ""; if (mapping.OutputParameterProperty != null) { outputPath += ".set" + CodeNamer.PascalCase(mapping.OutputParameterProperty); return(string.Format(CultureInfo.InvariantCulture, "{0}({1})", outputPath, inputPath)); } else { return(string.Format(CultureInfo.InvariantCulture, "{0} = {1}", outputPath, inputPath)); } }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } PrimaryType primaryType = type as PrimaryType; if (defaultValue != null && primaryType != null) { if (primaryType.Type == KnownPrimaryType.String) { return(CodeNamer.QuoteValue(defaultValue, quoteChar: "'")); } else if (primaryType.Type == KnownPrimaryType.Boolean) { return(defaultValue.ToLowerInvariant()); } else { if (primaryType.Type == KnownPrimaryType.Date || primaryType.Type == KnownPrimaryType.DateTime || primaryType.Type == KnownPrimaryType.DateTimeRfc1123) { return("new Date('" + defaultValue + "')"); } else if (primaryType.Type == KnownPrimaryType.TimeSpan) { return("moment.duration('" + defaultValue + "')"); } else if (primaryType.Type == KnownPrimaryType.ByteArray) { return("new Buffer('" + defaultValue + "')"); } } } return(defaultValue); }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } PrimaryType primaryType = type as PrimaryType; if (defaultValue != null) { if (type is CompositeType) { return(type.Name + "{}"); } else if (primaryType != null) { if (primaryType.Type == KnownPrimaryType.String || primaryType.Type == KnownPrimaryType.Uuid || primaryType.Type == KnownPrimaryType.TimeSpan) { return(CodeNamer.QuoteValue(defaultValue)); } else if (primaryType.Type == KnownPrimaryType.Boolean) { return(defaultValue.ToLowerInvariant()); } else if (primaryType.Type == KnownPrimaryType.ByteArray) { return("[]bytearray(\"" + defaultValue + "\")"); } else { //TODO: handle imports for package types. } } } return(defaultValue); }
/// <summary> /// Adds method to use for autopagination. /// </summary> /// <param name="serviceClient">The service client.</param> private void AddRubyPageableMethod(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException(nameof(serviceClient)); } for (int i = 0; i < serviceClient.Methods.Count; i++) { Method method = serviceClient.Methods[i]; if (method.Extensions.ContainsKey(AzureExtensions.PageableExtension)) { PageableExtension pageableExtension = JsonConvert.DeserializeObject <PageableExtension>(method.Extensions[AzureExtensions.PageableExtension].ToString()); if (pageableExtension != null && !method.Extensions.ContainsKey("nextLinkMethod") && !string.IsNullOrWhiteSpace(pageableExtension.NextLinkName)) { if (method.Extensions.ContainsKey("nextMethodName")) { method.Extensions["nextMethodName"] = CodeNamer.GetMethodName((string)method.Extensions["nextMethodName"]); } else if (!string.IsNullOrWhiteSpace(pageableExtension.OperationName)) { method.Extensions["nextMethodName"] = CodeNamer.GetMethodName(pageableExtension.OperationName); } if (!method.Extensions.ContainsKey(AzureExtensions.LongRunningExtension)) { serviceClient.Methods.Insert(i, (Method)method.Clone()); i++; } } if (!method.Extensions.ContainsKey(AzureExtensions.LongRunningExtension) || method.Extensions.ContainsKey("nextLinkMethod")) { serviceClient.Methods[i].Extensions.Remove(AzureExtensions.PageableExtension); } } } }
public void CamelCase(string expected, string value) { var result = CodeNamer.CamelCase(value); Assert.Equal(expected, result); }
/// <summary> /// Generates Ruby code for Azure service client. /// </summary> /// <param name="cm">The code model.</param> /// <returns>Async tasks which generates SDK files.</returns> public override async Task Generate(CodeModel cm) { var codeModel = cm as CodeModelRba; if (codeModel == null) { throw new InvalidCastException("CodeModel is not a Azure Ruby code model."); } // Service client var serviceClientTemplate = new ServiceClientTemplate { Model = codeModel }; await Write(serviceClientTemplate, Path.Combine(GeneratorSettingsRba.Instance.sdkPath, CodeNamer.UnderscoreCase(codeModel.Name) + ImplementationFileExtension)); // Operations foreach (MethodGroupRba group in codeModel.Operations.Where(each => !each.IsCodeModelMethodGroup)) { // Operation var operationsTemplate = new AzureMethodGroupTemplate { Model = group }; await Write(operationsTemplate, Path.Combine(GeneratorSettingsRba.Instance.sdkPath, CodeNamer.UnderscoreCase(operationsTemplate.Model.TypeName) + ImplementationFileExtension)); } // Models foreach (CompositeTypeRba model in codeModel.ModelTypes) { if ((model.Extensions.ContainsKey(AzureExtensions.ExternalExtension) && (bool)model.Extensions[AzureExtensions.ExternalExtension])) { continue; } if (codeModel.pageModels.Any(each => each.Name.EqualsIgnoreCase(model.Name))) { // Skip, handled in the .pageModels section below. continue; } var modelTemplate = new AzureModelTemplate { Model = model }; if (!CompositeTypeRba.resourceOrSubResourceRegEx.IsMatch(model.Name) || !CompositeTypeRba.IsResourceModelMatchingStandardDefinition(model)) { await Write(modelTemplate, Path.Combine(GeneratorSettingsRb.Instance.modelsPath, CodeNamer.UnderscoreCase(model.Name) + ImplementationFileExtension)); } } // Paged Models foreach (var pageModel in codeModel.pageModels) { var pageTemplate = new PageModelTemplate { Model = pageModel }; await Write(pageTemplate, Path.Combine(GeneratorSettingsRb.Instance.modelsPath, CodeNamer.UnderscoreCase(pageModel.Name) + ImplementationFileExtension)); } // Enums foreach (EnumTypeRb enumType in codeModel.EnumTypes) { var enumTemplate = new EnumTemplate { Model = enumType }; await Write(enumTemplate, Path.Combine(GeneratorSettingsRb.Instance.modelsPath, CodeNamer.UnderscoreCase(enumTemplate.Model.Name) + ImplementationFileExtension)); } // Requirements var requirementsTemplate = new RequirementsTemplate { Model = new RequirementsRba(codeModel, this) }; await Write(requirementsTemplate, CodeNamer.UnderscoreCase(GeneratorSettingsRb.Instance.packageName ?? GeneratorSettingsRb.Instance.sdkName) + ImplementationFileExtension); // Version File if (GeneratorSettingsRb.Instance.packageVersion != null) { var versionTemplate = new VersionTemplate { Model = GeneratorSettingsRb.Instance.packageVersion }; await Write(versionTemplate, Path.Combine(GeneratorSettingsRb.Instance.sdkPath, "version" + ImplementationFileExtension)); } // Module Definition File if (Settings.Instance.Namespace != null) { var modTemplate = new ModuleDefinitionTemplate { Model = GeneratorSettingsRb.Instance.ModuleDeclarations }; await Write(modTemplate, Path.Combine(GeneratorSettingsRb.Instance.sdkPath, "module_definition" + ImplementationFileExtension)); } }
/// <summary> /// Normalizes client model using Azure-specific extensions. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> /// <param name="codeNamer">AutoRest settings</param> /// <returns></returns> public static void NormalizeAzureClientModel(ServiceClient serviceClient, Settings settings, CodeNamer codeNamer) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } settings.AddCredentials = true; // This extension from general extensions must be run prior to Azure specific extensions. ProcessParameterizedHost(serviceClient, settings); ProcessClientRequestIdExtension(serviceClient); UpdateHeadMethods(serviceClient); ParseODataExtension(serviceClient); FlattenModels(serviceClient); FlattenMethodParameters(serviceClient, settings); ParameterGroupExtensionHelper.AddParameterGroups(serviceClient); AddLongRunningOperations(serviceClient); AddAzureProperties(serviceClient); SetDefaultResponses(serviceClient); AddPageableMethod(serviceClient, codeNamer); }
/// <summary> /// Adds ListNext() method for each List method with x-ms-pageable extension. /// </summary> /// <param name="serviceClient"></param> /// <param name="codeNamer"></param> public static void AddPageableMethod(ServiceClient serviceClient, CodeNamer codeNamer) { if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.ToArray()) { if (method.Extensions.ContainsKey(PageableExtension)) { var pageableExtension = JsonConvert.DeserializeObject <PageableExtension>(method.Extensions[PageableExtension].ToString()); if (string.IsNullOrWhiteSpace(pageableExtension.NextLinkName)) { continue; } Method nextLinkMethod = null; if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod = serviceClient.Methods.FirstOrDefault(m => pageableExtension.OperationName.Equals(m.SerializedName, StringComparison.OrdinalIgnoreCase)); if (nextLinkMethod != null) { nextLinkMethod.Extensions["nextLinkMethod"] = true; } } if (nextLinkMethod == null) { nextLinkMethod = (Method)method.Clone(); if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod.Name = codeNamer.GetMethodName(SwaggerModeler.GetMethodName( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); nextLinkMethod.Group = codeNamer.GetMethodGroupName(SwaggerModeler.GetMethodGroup( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); } else { nextLinkMethod.Name = nextLinkMethod.Name + "Next"; } method.Extensions["nextMethodName"] = nextLinkMethod.Name; method.Extensions["nextMethodGroup"] = nextLinkMethod.Group; nextLinkMethod.Extensions["nextLinkMethod"] = true; nextLinkMethod.Parameters.Clear(); nextLinkMethod.Url = "{nextLink}"; nextLinkMethod.IsAbsoluteUrl = true; var nextLinkParameter = new Parameter { Name = "nextPageLink", SerializedName = "nextLink", Type = new PrimaryType(KnownPrimaryType.String), Documentation = "The NextLink from the previous successful call to List operation.", IsRequired = true, Location = ParameterLocation.Path }; nextLinkParameter.Extensions[SkipUrlEncodingExtension] = true; nextLinkMethod.Parameters.Add(nextLinkParameter); // Need copy all the header parameters from List method to ListNext method foreach (var param in method.Parameters.Where(p => p.Location == ParameterLocation.Header)) { nextLinkMethod.Parameters.Add((Parameter)param.Clone()); } // Copy all grouped parameters that only contain header parameters nextLinkMethod.InputParameterTransformation.Clear(); method.InputParameterTransformation.GroupBy(t => t.ParameterMappings[0].InputParameter) .ForEach(grouping => { if (grouping.All(t => t.OutputParameter.Location == ParameterLocation.Header)) { // All grouped properties were header parameters, reuse data type nextLinkMethod.Parameters.Add(grouping.Key); grouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add(t)); } else if (grouping.Any(t => t.OutputParameter.Location == ParameterLocation.Header)) { // Some grouped properties were header parameters, creating new data types var headerGrouping = grouping.Where(t => t.OutputParameter.Location == ParameterLocation.Header); headerGrouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add((ParameterTransformation)t.Clone())); var newGroupingParam = CreateParameterFromGrouping(headerGrouping, nextLinkMethod, serviceClient); nextLinkMethod.Parameters.Add(newGroupingParam); //grouping.Key.Name = newGroupingParam.Name; var inputParameter = (Parameter)nextLinkMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter.Clone(); inputParameter.Name = codeNamer.GetParameterName(newGroupingParam.Name); nextLinkMethod.InputParameterTransformation.ForEach(t => t.ParameterMappings[0].InputParameter = inputParameter); } }); serviceClient.Methods.Add(nextLinkMethod); } } } }
/// <summary> /// Adds ListNext() method for each List method with x-ms-pageable extension. /// </summary> /// <param name="serviceClient"></param> /// <param name="codeNamer"></param> public static void AddPageableMethod(ServiceClient serviceClient, CodeNamer codeNamer) { if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.ToArray()) { if (method.Extensions.ContainsKey(PageableExtension)) { var pageableExtension = JsonConvert.DeserializeObject <PageableExtension>(method.Extensions[PageableExtension].ToString()); if (string.IsNullOrWhiteSpace(pageableExtension.NextLinkName)) { continue; } Method nextLinkMethod = null; if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod = serviceClient.Methods.FirstOrDefault(m => pageableExtension.OperationName.Equals(m.SerializedName, StringComparison.OrdinalIgnoreCase)); } if (nextLinkMethod == null) { nextLinkMethod = (Method)method.Clone(); if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod.Name = codeNamer.GetMethodName(SwaggerModeler.GetMethodName( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); nextLinkMethod.Group = codeNamer.GetMethodGroupName(SwaggerModeler.GetMethodGroup( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); } else { nextLinkMethod.Name = nextLinkMethod.Name + "Next"; } nextLinkMethod.Parameters.Clear(); nextLinkMethod.Url = "{nextLink}"; nextLinkMethod.IsAbsoluteUrl = true; var nextLinkParameter = new Parameter { Name = "nextPageLink", SerializedName = "nextLink", Type = PrimaryType.String, Documentation = "The NextLink from the previous successful call to List operation.", IsRequired = true, Location = ParameterLocation.Path }; nextLinkParameter.Extensions[SkipUrlEncodingExtension] = true; nextLinkMethod.Parameters.Add(nextLinkParameter); // Need copy all the header parameters from List method to ListNext method foreach (var param in method.Parameters.Where(p => p.Location == ParameterLocation.Header)) { nextLinkMethod.Parameters.Add((Parameter)param.Clone()); } serviceClient.Methods.Add(nextLinkMethod); } } } }
/// <summary> /// The sequence is critical: the templates will be executed in the order of the returned list. /// But it will be put into another position you specified in the target file. /// </summary> /// <returns>The generators as well as its target file name and position in file.</returns> private IEnumerable <(ITfProviderGenerator Generator, uint ExecutionNumber, string TargetFile, uint PositionInFile)> CreateGeneratorDescriptors() { var resourceName = Settings.Metadata.ResourceName; var resourceFileName = CodeNamer.GetResourceFileName(resourceName) + ImplementationFileExtension; return(new (ITfProviderGenerator, uint, string, uint)[]
/// <summary> /// Converts the specified string to a camel cased string. /// </summary> /// <param name="value">The string to convert.</param> /// <returns>The camel case string.</returns> public static string ToCamelCase(this string value) { return(CodeNamer.CamelCase(value)); }
public override string EscapeDefaultValue(string defaultValue, IType type) { if (type == null) { throw new ArgumentNullException("type"); } var parsedDefault = PythonConstants.None; EnumType enumType = type as EnumType; if (defaultValue != null && enumType != null) { parsedDefault = CodeNamer.QuoteValue(defaultValue); } PrimaryType primaryType = type as PrimaryType; if (defaultValue != null && primaryType != null) { if (primaryType.Type == KnownPrimaryType.String || primaryType.Type == KnownPrimaryType.Uuid) { parsedDefault = CodeNamer.QuoteValue(defaultValue); } else if (primaryType.Type == KnownPrimaryType.Boolean) { if (defaultValue == "true") { parsedDefault = "True"; } else { parsedDefault = "False"; } } else { //TODO: Add support for default KnownPrimaryType.DateTimeRfc1123 //TODO: Default date objects can only be supported with an isodate import statement //if (primaryType.Type == KnownPrimaryType.Date) //{ // parsedDefault = "isodate.parse_date(\"" + defaultValue + "\")"; //} //else if (primaryType.Type == KnownPrimaryType.DateTime) //{ // parsedDefault = "isodate.parse_datetime(\"" + defaultValue + "\")"; //} //else if (primaryType.Type == KnownPrimaryType.TimeSpan) //{ // parsedDefault = "isodate.parse_duration(\"" + defaultValue + "\")"; //} if (primaryType.Type == KnownPrimaryType.ByteArray) { parsedDefault = "bytearray(\"" + defaultValue + "\", encoding=\"utf-8\")"; } else if (primaryType.Type == KnownPrimaryType.Int || primaryType.Type == KnownPrimaryType.Long || primaryType.Type == KnownPrimaryType.Double) { parsedDefault = defaultValue; } } } return(parsedDefault); }
/// <summary> /// Normalizes client model using Azure-specific extensions. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> /// <param name="codeNamer">AutoRest settings</param> /// <returns></returns> public static void NormalizeAzureClientModel(ServiceClient serviceClient, Settings settings, CodeNamer codeNamer) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } settings.AddCredentials = true; UpdateHeadMethods(serviceClient); ParseODataExtension(serviceClient); FlattenResourceProperties(serviceClient); FlattenRequestPayload(serviceClient, settings); AddLongRunningOperations(serviceClient); AddAzureProperties(serviceClient); SetDefaultResponses(serviceClient); AddPageableMethod(serviceClient, codeNamer); AddParameterGroups(serviceClient); //This should come after all methods have been dynamically added }
/// <summary> /// Adds ListNext() method for each List method with x-ms-pageable extension. /// </summary> /// <param name="serviceClient"></param> /// <param name="codeNamer"></param> public static void AddPageableMethod(ServiceClient serviceClient, CodeNamer codeNamer) { if (codeNamer == null) { throw new ArgumentNullException("codeNamer"); } if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.ToArray()) { if (method.Extensions.ContainsKey(PageableExtension)) { var pageableExtension = JsonConvert.DeserializeObject<PageableExtension>(method.Extensions[PageableExtension].ToString()); if (string.IsNullOrWhiteSpace(pageableExtension.NextLinkName)) { continue; } Method nextLinkMethod = null; if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod = serviceClient.Methods.FirstOrDefault(m => pageableExtension.OperationName.Equals(m.SerializedName, StringComparison.OrdinalIgnoreCase)); if (nextLinkMethod != null) { nextLinkMethod.Extensions["nextLinkMethod"] = true; } } if (nextLinkMethod == null) { nextLinkMethod = (Method)method.Clone(); if (!string.IsNullOrEmpty(pageableExtension.OperationName)) { nextLinkMethod.Name = codeNamer.GetMethodName(SwaggerModeler.GetMethodName( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); nextLinkMethod.Group = codeNamer.GetMethodGroupName(SwaggerModeler.GetMethodGroup( new Rest.Modeler.Swagger.Model.Operation { OperationId = pageableExtension.OperationName })); } else { nextLinkMethod.Name = nextLinkMethod.Name + "Next"; } method.Extensions["nextMethodName"] = nextLinkMethod.Name; method.Extensions["nextMethodGroup"] = nextLinkMethod.Group; nextLinkMethod.Extensions["nextLinkMethod"] = true; nextLinkMethod.Parameters.Clear(); nextLinkMethod.Url = "{nextLink}"; nextLinkMethod.IsAbsoluteUrl = true; var nextLinkParameter = new Parameter { Name = "nextPageLink", SerializedName = "nextLink", Type = new PrimaryType(KnownPrimaryType.String), Documentation = "The NextLink from the previous successful call to List operation.", IsRequired = true, Location = ParameterLocation.Path }; nextLinkParameter.Extensions[SkipUrlEncodingExtension] = true; nextLinkMethod.Parameters.Add(nextLinkParameter); // Need copy all the header parameters from List method to ListNext method foreach (var param in method.Parameters.Where(p => p.Location == ParameterLocation.Header)) { nextLinkMethod.Parameters.Add((Parameter)param.Clone()); } // Copy all grouped parameters that only contain header parameters nextLinkMethod.InputParameterTransformation.Clear(); method.InputParameterTransformation.GroupBy(t => t.ParameterMappings[0].InputParameter) .ForEach(grouping => { if (grouping.All(t => t.OutputParameter.Location == ParameterLocation.Header)) { // All grouped properties were header parameters, reuse data type nextLinkMethod.Parameters.Add(grouping.Key); grouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add(t)); } else if (grouping.Any(t => t.OutputParameter.Location == ParameterLocation.Header)) { // Some grouped properties were header parameters, creating new data types var headerGrouping = grouping.Where(t => t.OutputParameter.Location == ParameterLocation.Header); headerGrouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add((ParameterTransformation) t.Clone())); var newGroupingParam = CreateParameterFromGrouping(headerGrouping, nextLinkMethod, serviceClient); nextLinkMethod.Parameters.Add(newGroupingParam); //grouping.Key.Name = newGroupingParam.Name; var inputParameter = (Parameter) nextLinkMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter.Clone(); inputParameter.Name = newGroupingParam.Name.ToCamelCase(); nextLinkMethod.InputParameterTransformation.ForEach(t => t.ParameterMappings[0].InputParameter = inputParameter); } }); serviceClient.Methods.Add(nextLinkMethod); } } } }
/// <summary> /// Converts the specified string to a pascal cased string. /// </summary> /// <param name="value">The string to convert.</param> /// <returns>The pascal case string.</returns> public static string ToPascalCase(this string value) { return(CodeNamer.PascalCase(value)); }