public Parameter Build() { string parameterName = _swaggerParameter.Name; SwaggerParameter unwrappedParameter = _swaggerParameter; if (_swaggerParameter.Reference != null) { unwrappedParameter = Modeler.Unwrap(_swaggerParameter); } if (unwrappedParameter.Schema != null && unwrappedParameter.Schema.Reference != null) { parameterName = unwrappedParameter.Schema.Reference.StripDefinitionPath(); } if (parameterName == null) { parameterName = unwrappedParameter.Name; } IType parameterType = BuildServiceType(parameterName); var parameter = new Parameter { Name = unwrappedParameter.Name, SerializedName = unwrappedParameter.Name, Type = parameterType, IsRequired = unwrappedParameter.IsRequired, Location = (Generator.ClientModel.ParameterLocation)Enum.Parse(typeof(Generator.ClientModel.ParameterLocation), unwrappedParameter.In.ToString()) }; parameter.IsRequired = parameter.IsRequired || parameter.Location == Generator.ClientModel.ParameterLocation.Path; parameter.CollectionFormat = unwrappedParameter.CollectionFormat; parameter.Documentation = unwrappedParameter.Description; if(_swaggerParameter.Reference != null) { var clientProperty = Modeler.ServiceClient.Properties.First(p => p.Name == unwrappedParameter.Name); parameter.ClientProperty = clientProperty; } var enumType = parameterType as EnumType; if (enumType != null) { if (parameter.Documentation == null) { parameter.Documentation = string.Empty; } else { parameter.Documentation = parameter.Documentation.TrimEnd('.') + ". "; } parameter.Documentation += "Possible values for this parameter include: " + string.Join(", ", enumType.Values.Select(v => string.Format(CultureInfo.InvariantCulture, "'{0}'", v.Name))); } unwrappedParameter.Extensions.ForEach(e => parameter.Extensions[e.Key] = e.Value); return parameter; }
/// <summary> /// Format the value of a sequence given the modeled element format. Note that only sequences of strings are supported /// </summary> /// <param name="parameter">The parameter to format</param> /// <returns>return the separator</returns> public static string NeedsFormattedSeparator(Parameter parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } SequenceType sequence = parameter.Type as SequenceType; if (sequence == null) { return null; } PrimaryType primaryType = sequence.ElementType as PrimaryType; EnumType enumType = sequence.ElementType as EnumType; if (enumType != null) { primaryType = PrimaryType.String; } if (primaryType != PrimaryType.String) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Cannot generate a formatted sequence from a " + "non-string array parameter {0}", parameter)); } return parameter.CollectionFormat.GetSeparator(); }
private void BuildOptionsParameterTemplateModel() { CompositeType optionsType; optionsType = new CompositeType { Name = "options", SerializedName = "options", Documentation = "Optional Parameters." }; var optionsParmeter = new Parameter { Name = "options", SerializedName = "options", IsRequired = false, Documentation = "Optional Parameters.", Location = ParameterLocation.None, Type = optionsType }; IEnumerable<ParameterTemplateModel> optionalParameters = LocalParameters.Where(p => !p.IsRequired); foreach (ParameterTemplateModel parameter in optionalParameters) { Property optionalProperty = new Property { IsReadOnly = false, Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = parameter.SerializedName }; parameter.Constraints.ToList().ForEach(x => optionalProperty.Constraints.Add(x.Key, x.Value)); parameter.Extensions.ToList().ForEach(x => optionalProperty.Extensions.Add(x.Key, x.Value)); ((CompositeType)optionsParmeter.Type).Properties.Add(optionalProperty); } //Adding customHeaders to the options object Property customHeaders = new Property { IsReadOnly = false, Name = "customHeaders", IsRequired = false, Documentation = "Headers that will be added to the request", Type = new PrimaryType(KnownPrimaryType.Object), SerializedName = "customHeaders" }; ((CompositeType)optionsParmeter.Type).Properties.Add(customHeaders); OptionsParameterTemplateModel = new ParameterTemplateModel(optionsParmeter); }
public ParameterModel(Parameter parameter, Method method) : base() { this.LoadFrom(parameter); this._method = method; // Use instance type for optional parameters if (!this.IsRequired) { this.Type = ((ITypeModel) Type).InstanceType(); } _wireName = this.Name.ToCamelCase(); if (NeedsConversion) { _wireName += "Converted"; } _implImports = new List<string>(); }
public void ParseWithServiceClientWithCreateResourceMethod() { ServiceClient serviceClient = new ServiceClient(); Parameter body = new Parameter() { Location = ParameterLocation.Body, Type = new CompositeType(), }; CompositeType responseBody = new CompositeType(); responseBody.Extensions.Add("x-ms-azure-resource", true); const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}"; Method method = CreateMethod(body: body, responseBody: responseBody, url: url); serviceClient.Methods.Add(method); IDictionary<string, ResourceSchema> schemas = ResourceSchemaParser.Parse(serviceClient); Assert.NotNull(schemas); Assert.Equal(1, schemas.Count); ResourceSchema schema = schemas["Mock.Provider"]; Assert.Null(schema.Id); Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema); Assert.Equal("Mock.Provider", schema.Title); Assert.Equal("Mock Provider Resource Types", schema.Description); Assert.Equal(1, schema.ResourceDefinitions.Count); Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single()); Assert.Equal( new JsonSchema() { JsonType = "object", Description = "Mock.Provider/mockResourceNames" } .AddProperty("type", new JsonSchema() { JsonType = "string" } .AddEnum("Mock.Provider/mockResourceNames"), true), schema.ResourceDefinitions["mockResourceNames"]); Assert.NotNull(schema.Definitions); Assert.Equal(0, schema.Definitions.Count); }
public Parameter Build() { string parameterName = _swaggerParameter.Name; SwaggerParameter unwrappedParameter = _swaggerParameter; if (_swaggerParameter.Reference != null) { unwrappedParameter = Modeler.Unwrap(_swaggerParameter); } if (unwrappedParameter.Schema != null && unwrappedParameter.Schema.Reference != null) { parameterName = unwrappedParameter.Schema.Reference.StripDefinitionPath(); } if (parameterName == null) { parameterName = unwrappedParameter.Name; } IType parameterType = BuildServiceType(parameterName); var parameter = new Parameter { Name = unwrappedParameter.Name, SerializedName = unwrappedParameter.Name, Type = parameterType, Location = (Generator.ClientModel.ParameterLocation)Enum.Parse(typeof(Generator.ClientModel.ParameterLocation), unwrappedParameter.In.ToString()) }; parameter.IsRequired = parameter.IsRequired || parameter.Location == Generator.ClientModel.ParameterLocation.Path; PopulateParameter(parameter, unwrappedParameter); if (_swaggerParameter.Reference != null) { var clientProperty = Modeler.ServiceClient.Properties.FirstOrDefault(p => p.SerializedName == unwrappedParameter.Name); parameter.ClientProperty = clientProperty; } return parameter; }
public void VerifyInputMappingsForFlattening() { var serviceClient = new ServiceClient(); serviceClient.Name = "test service client"; var customObjectType = new CompositeType(); customObjectType.Name = "Foo"; customObjectType.Properties.Add(new Property { Name = "A", Type = PrimaryType.Boolean }); customObjectType.Properties.Add(new Property { Name = "B", Type = PrimaryType.String }); var method = new Method { Name = "method1", Group = "mGroup", ReturnType = new Response(customObjectType, null) }; var outputParameter = new Parameter { Name = "body", Type = customObjectType }; serviceClient.Methods.Add(method); method.Parameters.Add(new Parameter { Name = "paramA", Type = PrimaryType.Boolean, SerializedName = "paramA" }); method.Parameters.Add(new Parameter { Name = "paramB", Type = PrimaryType.String, SerializedName = "paramB" }); method.InputParameterTransformation.Add(new ParameterTransformation { OutputParameter = outputParameter }); method.InputParameterTransformation[0].ParameterMappings.Add(new ParameterMapping { InputParameter = method.Parameters[0], OutputParameterProperty = "A" }); method.InputParameterTransformation[0].ParameterMappings.Add(new ParameterMapping { InputParameter = method.Parameters[1], OutputParameterProperty = "B" }); MethodTemplateModel templateModel = new MethodTemplateModel(method, serviceClient); var output = templateModel.BuildInputMappings(); string expected = @"Foo body = null; if (paramA != null || paramB != null) { body = new Foo(); body.A = paramA; body.B = paramB; }"; MultilineAreEqual(expected, output.Trim()); }
/// <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> /// Initializes a new instance of the AzureParameterTemplateModel class. /// </summary> /// <param name="source">The source.</param> public AzureParameterTemplateModel(Parameter source) : base(source) { }
/// <summary> /// Provides the parameter documentation string. /// </summary> /// <param name="parameter">Parameter to be documented</param> /// <returns>Parameter documentation string correct notation</returns> public static string GetParameterDocumentationString(Parameter parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } string docString = ":param "; docString += parameter.Name + ":"; if (!string.IsNullOrWhiteSpace(parameter.Documentation)) { docString += " " + parameter.Documentation; } return docString; }
private static string BuildSerializeDataCall(Parameter parameter, string functionName) { string divChar = ClientModelExtensions.NeedsFormattedSeparator(parameter); string divParameter = string.Empty; if (!string.IsNullOrEmpty(divChar)) { divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar); } //TODO: This creates a very long line - break it up over multiple lines. return string.Format(CultureInfo.InvariantCulture, "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4}{5})", functionName, parameter.Name, parameter.Type.ToPythonRuntimeTypeString(), parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty, divParameter, BuildValidationParameters(parameter.Constraints)); }
public ParameterTemplateModel(Parameter source) { this.LoadFrom(source); }
/// <summary> /// Provides the parameter name in the correct jsdoc notation depending on /// whether it is required or optional /// </summary> /// <param name="parameter">Parameter to be documented</param> /// <returns>Parameter name in the correct jsdoc notation</returns> public static string GetParameterDocumentationName(Parameter parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } if (parameter.IsRequired) { return parameter.Name; } else { return string.Format(CultureInfo.InvariantCulture, "[{0}]", parameter.Name); } }
/// <summary> /// Flattens the request payload if the number of properties of the /// payload is less than or equal to the PayloadFlatteningThreshold. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> public static void FlattenMethodParameters(ServiceClient serviceClient, Settings settings) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } foreach (var method in serviceClient.Methods) { var bodyParameter = method.Parameters.FirstOrDefault( p => p.Location == ClientModel.ParameterLocation.Body); if (bodyParameter != null) { var bodyParameterType = bodyParameter.Type as CompositeType; if (bodyParameterType != null && (bodyParameterType.ComposedProperties.Count(p => !p.IsConstant) <= settings.PayloadFlatteningThreshold || bodyParameter.ShouldBeFlattened())) { var parameterTransformation = new ParameterTransformation { OutputParameter = bodyParameter }; method.InputParameterTransformation.Add(parameterTransformation); foreach (var property in bodyParameterType.ComposedProperties.Where(p => !p.IsConstant && p.Name != null)) { var newMethodParameter = new Parameter(); newMethodParameter.LoadFrom(property); bodyParameter.Extensions.ForEach(kv => { newMethodParameter.Extensions[kv.Key] = kv.Value; }); method.Parameters.Add(newMethodParameter); parameterTransformation.ParameterMappings.Add(new ParameterMapping { InputParameter = newMethodParameter, OutputParameterProperty = property.GetClientName() }); } method.Parameters.Remove(bodyParameter); } } } }
/// <summary> /// Adds the parameter groups to operation parameters. /// </summary> /// <param name="serviceClient"></param> public static void AddParameterGroups(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } HashSet<CompositeType> generatedParameterGroups = new HashSet<CompositeType>(); foreach (Method method in serviceClient.Methods) { //This group name is normalized by each languages code generator later, so it need not happen here. Dictionary<string, Dictionary<Property, Parameter>> parameterGroups = new Dictionary<string, Dictionary<Property, Parameter>>(); foreach (Parameter parameter in method.Parameters) { if (parameter.Extensions.ContainsKey(ParameterGroupExtension)) { Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as Newtonsoft.Json.Linq.JContainer; if (extensionObject != null) { string specifiedGroupName = extensionObject.Value<string>("name"); string parameterGroupName; if (specifiedGroupName == null) { string postfix = extensionObject.Value<string>("postfix") ?? "Parameters"; parameterGroupName = method.Group + "-" + method.Name + "-" + postfix; } else { parameterGroupName = specifiedGroupName; } if (!parameterGroups.ContainsKey(parameterGroupName)) { parameterGroups.Add(parameterGroupName, new Dictionary<Property, Parameter>()); } Property groupProperty = new Property() { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = null //Parameter is never serialized directly }; parameterGroups[parameterGroupName].Add(groupProperty, parameter); } } } foreach (string parameterGroupName in parameterGroups.Keys) { CompositeType parameterGroupType = generatedParameterGroups.FirstOrDefault(item => item.Name == parameterGroupName); bool createdNewCompositeType = false; if (parameterGroupType == null) { parameterGroupType = new CompositeType() { Name = parameterGroupName, Documentation = "Additional parameters for the " + method.Name + " operation." }; generatedParameterGroups.Add(parameterGroupType); //Populate the parameter group type with properties. //Add to the service client serviceClient.ModelTypes.Add(parameterGroupType); createdNewCompositeType = true; } foreach (Property property in parameterGroups[parameterGroupName].Keys) { //Either the paramter group is "empty" since it is new, or it is "full" and we don't allow different schemas if (createdNewCompositeType) { parameterGroupType.Properties.Add(property); } else { Property matchingProperty = parameterGroupType.Properties.FirstOrDefault( item => item.Name == property.Name && item.IsReadOnly == property.IsReadOnly && item.DefaultValue == property.DefaultValue && item.SerializedName == property.SerializedName); if (matchingProperty == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Property {0} was specified on group {1} but it is not on shared parameter group object {2}", property.Name, method.Name, parameterGroupType.Name)); } } } bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type Parameter parameterGroup = new Parameter() { Name = parameterGroupName, IsRequired = isGroupParameterRequired, Location = ParameterLocation.None, SerializedName = string.Empty, Type = parameterGroupType, Documentation = "Additional parameters for the operation" }; method.Parameters.Add(parameterGroup); //Link the grouped parameters to their parent, and remove them from the method parameters foreach (Property property in parameterGroups[parameterGroupName].Keys) { Parameter p = parameterGroups[parameterGroupName][property]; var parameterTransformation = new ParameterTransformation { OutputParameter = p }; parameterTransformation.ParameterMappings.Add(new ParameterMapping { InputParameter = parameterGroup, InputParameterProperty = property.Name }); method.InputParameterTransformation.Add(parameterTransformation); method.Parameters.Remove(p); } } } }
/// <summary> /// Flattens the request payload if the number of properties of the /// payload is less than or equal to the PayloadFlatteningThreshold. /// </summary> /// <param name="serviceClient">Service client</param> /// <param name="settings">AutoRest settings</param> public static void FlattenRequestPayload(ServiceClient serviceClient, Settings settings) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (settings == null) { throw new ArgumentNullException("settings"); } foreach (var method in serviceClient.Methods) { var bodyParameter = method.Parameters.FirstOrDefault( p => p.Location == ParameterLocation.Body); if (bodyParameter != null) { var bodyParameterType = bodyParameter.Type as CompositeType; if (bodyParameterType != null && bodyParameterType.ComposedProperties.Count(p => !p.IsConstant) <= settings.PayloadFlatteningThreshold) { var parameterTransformation = new ParameterTransformation { OutputParameter = bodyParameter }; method.InputParameterTransformation.Add(parameterTransformation); foreach (var property in bodyParameterType.ComposedProperties.Where(p => !p.IsConstant)) { var newMethodParameter = new Parameter(); newMethodParameter.LoadFrom(property); method.Parameters.Add(newMethodParameter); parameterTransformation.ParameterMappings.Add(new ParameterMapping { InputParameter = newMethodParameter, OutputParameterProperty = property.Name }); } method.Parameters.Remove(bodyParameter); } } } }
public void VerifyInputMappingsForGrouping() { var serviceClient = new ServiceClient(); serviceClient.Name = "test service client"; var customObjectType = new CompositeType(); customObjectType.Name = "Foo"; customObjectType.Properties.Add(new Property { Name = "A", Type = PrimaryType.Boolean }); customObjectType.Properties.Add(new Property { Name = "B", Type = new PrimaryType(KnownPrimaryType.String) }); var method = new Method { Name = "method1", Group = "mGroup", ReturnType = new Response(customObjectType, null) }; var inputParameter = new Parameter { Name = "body", Type = customObjectType }; serviceClient.Methods.Add(method); method.Parameters.Add(inputParameter); method.InputParameterTransformation.Add(new ParameterTransformation { OutputParameter = new Parameter { Name = "paramA", Type = new PrimaryType(KnownPrimaryType.String), SerializedName = "paramA" } }); method.InputParameterTransformation.Last().ParameterMappings.Add(new ParameterMapping { InputParameter = inputParameter, InputParameterProperty = "A" }); method.InputParameterTransformation.Add(new ParameterTransformation { OutputParameter = new Parameter { Name = "paramB", Type = new PrimaryType(KnownPrimaryType.String), SerializedName = "paramB" } }); method.InputParameterTransformation.Last().ParameterMappings.Add(new ParameterMapping { InputParameter = inputParameter, InputParameterProperty = "B" }); MethodTemplateModel templateModel = new MethodTemplateModel(method, serviceClient); var output = templateModel.BuildInputMappings(); string expected = @"String paramA = null; if (body != null) { paramA = body.A; } String paramB = null; if (body != null) { paramB = body.B; }"; MultilineAreEqual(expected, output.Trim()); }
/// <summary> /// Adds the parameter groups to operation parameters. /// </summary> /// <param name="serviceClient"></param> public static void AddParameterGroups(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } HashSet<CompositeType> generatedParameterGroups = new HashSet<CompositeType>(); foreach (Method method in serviceClient.Methods) { //Copy out flattening transformations as they should be the last List<ParameterTransformation> flatteningTransformations = method.InputParameterTransformation.ToList(); method.InputParameterTransformation.Clear(); //This group name is normalized by each languages code generator later, so it need not happen here. Dictionary<string, Dictionary<Property, Parameter>> parameterGroups = new Dictionary<string, Dictionary<Property, Parameter>>(); foreach (Parameter parameter in method.Parameters) { if (parameter.Extensions.ContainsKey(ParameterGroupExtension)) { JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as JContainer; if (extensionObject != null) { string specifiedGroupName = extensionObject.Value<string>("name"); string parameterGroupName; if (specifiedGroupName == null) { string postfix = extensionObject.Value<string>("postfix") ?? "Parameters"; parameterGroupName = method.Group + "-" + method.Name + "-" + postfix; } else { parameterGroupName = specifiedGroupName; } if (!parameterGroups.ContainsKey(parameterGroupName)) { parameterGroups.Add(parameterGroupName, new Dictionary<Property, Parameter>()); } Property groupProperty = new Property() { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = null //Parameter is never serialized directly }; // Copy over extensions foreach (var key in parameter.Extensions.Keys) { groupProperty.Extensions[key] = parameter.Extensions[key]; } parameterGroups[parameterGroupName].Add(groupProperty, parameter); } } } foreach (string parameterGroupName in parameterGroups.Keys) { CompositeType parameterGroupType = generatedParameterGroups.FirstOrDefault(item => item.Name == parameterGroupName); if (parameterGroupType == null) { parameterGroupType = new CompositeType { Name = parameterGroupName, Documentation = "Additional parameters for the " + method.Name + " operation." }; generatedParameterGroups.Add(parameterGroupType); //Add to the service client serviceClient.ModelTypes.Add(parameterGroupType); } foreach (Property property in parameterGroups[parameterGroupName].Keys) { Property matchingProperty = parameterGroupType.Properties.FirstOrDefault( item => item.Name == property.Name && item.IsReadOnly == property.IsReadOnly && item.DefaultValue == property.DefaultValue && item.SerializedName == property.SerializedName); if (matchingProperty == null) { parameterGroupType.Properties.Add(property); } } bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type Parameter parameterGroup = new Parameter() { Name = parameterGroupName, IsRequired = isGroupParameterRequired, Location = ClientModel.ParameterLocation.None, SerializedName = string.Empty, Type = parameterGroupType, Documentation = "Additional parameters for the operation" }; method.Parameters.Add(parameterGroup); //Link the grouped parameters to their parent, and remove them from the method parameters foreach (Property property in parameterGroups[parameterGroupName].Keys) { Parameter p = parameterGroups[parameterGroupName][property]; var parameterTransformation = new ParameterTransformation { OutputParameter = p }; parameterTransformation.ParameterMappings.Add(new ParameterMapping { InputParameter = parameterGroup, InputParameterProperty = property.GetClientName() }); method.InputParameterTransformation.Add(parameterTransformation); method.Parameters.Remove(p); } } // Copy back flattening transformations if any flatteningTransformations.ForEach(t => method.InputParameterTransformation.Add(t)); } }
private static Method CreateMethod(HttpMethod httpMethod = HttpMethod.Put, Parameter body = null, IType responseBody = null, string url = null) { Method method = new Method() { HttpMethod = httpMethod, ReturnType = new Response(responseBody, null), Url = url, }; method.Parameters.Add(body); return method; }
public virtual void NormalizeODataMethods(ServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } foreach (var method in client.Methods) { if (method.Extensions.ContainsKey(AzureExtensions.ODataExtension)) { var odataFilter = method.Parameters.FirstOrDefault(p => p.SerializedName.Equals("$filter", StringComparison.OrdinalIgnoreCase) && p.Location == ParameterLocation.Query && p.Type is CompositeType); if (odataFilter == null) { continue; } // Remove all odata parameters method.Parameters.RemoveAll(source => (source.SerializedName.Equals("$filter", StringComparison.OrdinalIgnoreCase) || source.SerializedName.Equals("$top", StringComparison.OrdinalIgnoreCase) || source.SerializedName.Equals("$orderby", StringComparison.OrdinalIgnoreCase) || source.SerializedName.Equals("$skip", StringComparison.OrdinalIgnoreCase) || source.SerializedName.Equals("$expand", StringComparison.OrdinalIgnoreCase)) && source.Location == ParameterLocation.Query); var odataQuery = new Parameter { SerializedName = "$filter", Name = "odataQuery", Type = new CompositeType { Name = string.Format(CultureInfo.InvariantCulture, "ODataQuery<{0}>", odataFilter.Type.Name) }, Documentation = "OData parameters to apply to the operation.", Location = ParameterLocation.Query, IsRequired = odataFilter.IsRequired }; odataQuery.Extensions[AzureExtensions.ODataExtension] = method.Extensions[AzureExtensions.ODataExtension]; method.Parameters.Insert(0, odataQuery); } } }
public void VerifyInputMappingsForResources() { var serviceClient = new ServiceClient(); serviceClient.Name = "test service client"; var flattenedPropertyType = new CompositeType(); flattenedPropertyType.Name = "FooFlattened"; flattenedPropertyType.Properties.Add(new Property { Name = "Sku", Type = PrimaryType.String }); flattenedPropertyType.Properties.Add(new Property { Name = "ProvState", Type = PrimaryType.String }); flattenedPropertyType.Properties.Add(new Property { Name = "Id", Type = PrimaryType.Int }); var customObjectPropertyType = new CompositeType(); customObjectPropertyType.Name = "FooProperty"; customObjectPropertyType.Properties.Add(new Property { Name = "Sku", Type = PrimaryType.String }); customObjectPropertyType.Properties.Add(new Property { Name = "ProvState", Type = PrimaryType.String }); var customObjectType = new CompositeType(); customObjectType.Name = "Foo"; customObjectType.Properties.Add(new Property { Name = "Property", Type = customObjectPropertyType }); customObjectType.Properties.Add(new Property { Name = "Id", Type = PrimaryType.Int }); var method = new Method { Name = "method1", Group = "mGroup", ReturnType = new Response(flattenedPropertyType, null) }; var inputParameter = new Parameter { Name = "prop", Type = flattenedPropertyType }; serviceClient.Methods.Add(method); method.Parameters.Add(inputParameter); method.InputParameterTransformation.Add(new ParameterTransformation { OutputParameter = new Parameter { Name = "body", Type = customObjectType, SerializedName = "body" } }); method.InputParameterTransformation.Last().ParameterMappings.Add(new ParameterMapping { InputParameter = inputParameter, InputParameterProperty = "Id", OutputParameterProperty = "Id" }); method.InputParameterTransformation.Last().ParameterMappings.Add(new ParameterMapping { InputParameter = inputParameter, InputParameterProperty = "Sku", OutputParameterProperty = "Property.Sku" }); method.InputParameterTransformation.Last().ParameterMappings.Add(new ParameterMapping { InputParameter = inputParameter, InputParameterProperty = "ProvState", OutputParameterProperty = "Property.ProvState" }); MethodTemplateModel templateModel = new MethodTemplateModel(method, serviceClient); var output = templateModel.BuildInputMappings(); string expected = @"String paramA = null; if (body != null) { paramA = body.A; } String paramB = null; if (body != null) { paramB = body.B; }"; MultilineAreEqual(expected, output.Trim()); }
public static string GetParameterDocumentationType(Parameter parameter) { if (parameter == null) { throw new ArgumentNullException("parameter"); } string typeName = PrimaryType.Object.Name; if (parameter.Type is PrimaryType) { typeName = parameter.Type.Name; } else if (parameter.Type is SequenceType) { typeName = "array"; } else if (parameter.Type is EnumType) { typeName = PrimaryType.String.Name; } return typeName.ToLower(CultureInfo.InvariantCulture); }
/// <summary> /// Adds ListNext() method for each List method with x-ms-pageable extension. /// </summary> /// <param name="serviceClient"></param> public static void AddPageableMethod(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (var method in serviceClient.Methods.ToArray()) { if (method.Extensions.ContainsKey(PageableExtension)) { var newMethod = (Method) method.Clone(); newMethod.Name = newMethod.Name + "Next"; newMethod.Parameters.Clear(); newMethod.Url = "{nextLink}"; newMethod.IsAbsoluteUrl = true; var nextLinkParameter = new Parameter { Name = "nextLink", SerializedName = "nextLink", Type = PrimaryType.String, Documentation = "NextLink from the previous successful call to List operation.", IsRequired = true, Location = ParameterLocation.Path }; nextLinkParameter.Extensions[SkipUrlEncodingExtension] = true; newMethod.Parameters.Add(nextLinkParameter); serviceClient.Methods.Add(newMethod); } } }
private static string BuildSerializeDataCall(Parameter parameter, string functionName) { string divChar = ClientModelExtensions.NeedsFormattedSeparator(parameter); string divParameter = string.Empty; if (!string.IsNullOrEmpty(divChar)) { divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar); } return string.Format(CultureInfo.InvariantCulture, "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4})", functionName, parameter.Name, parameter.Type.ToPythonRuntimeTypeString(), parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty, divParameter); }
/// <summary> /// Adds the parameter groups to operation parameters. /// </summary> /// <param name="serviceClient"></param> public static void AddParameterGroups(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (Method method in serviceClient.Methods) { //This group name is normalized by each languages code generator later, so it need not happen here. Dictionary<string, Dictionary<Property, Parameter>> parameterGroups = new Dictionary<string, Dictionary<Property, Parameter>>(); foreach (Parameter parameter in method.Parameters) { if (parameter.Extensions.ContainsKey(ParameterGroupExtension)) { Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as Newtonsoft.Json.Linq.JContainer; if (extensionObject != null) { string parameterGroupName = method.Group + "-" + method.Name + "-" + "Parameters"; parameterGroupName = extensionObject.Value<string>("name") ?? parameterGroupName; if (!parameterGroups.ContainsKey(parameterGroupName)) { parameterGroups.Add(parameterGroupName, new Dictionary<Property, Parameter>()); } Property groupProperty = new Property() { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = null //Parameter is never serialized directly }; parameterGroups[parameterGroupName].Add(groupProperty, parameter); } } } foreach (string parameterGroupName in parameterGroups.Keys) { //Define the new parameter group type (it's always a composite type) CompositeType parameterGroupType = new CompositeType() { Name = parameterGroupName, Documentation = "Additional parameters for the " + method.Name + " operation." }; //Populate the parameter group type with properties. foreach (Property property in parameterGroups[parameterGroupName].Keys) { parameterGroupType.Properties.Add(property); } //Add to the service client serviceClient.ModelTypes.Add(parameterGroupType); bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type Parameter parameterGroup = new Parameter() { Name = parameterGroupName, IsRequired = isGroupParameterRequired, Location = ParameterLocation.None, SerializedName = string.Empty, Type = parameterGroupType, Documentation = "Additional parameters for the operation" }; method.Parameters.Add(parameterGroup); //Link the grouped parameters to their parent, and remove them from the method parameters foreach (Property property in parameterGroups[parameterGroupName].Keys) { Parameter p = parameterGroups[parameterGroupName][property]; method.InputParameterMappings.Add(new ParameterMapping { InputParameter = parameterGroup, OutputParameter = p, InputParameterProperty = property.Name }); method.Parameters.Remove(p); } } } }