Esempio n. 1
0
        /// <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 = new PrimaryType(KnownPrimaryType.String)
                {
                    Name = "str"
                };
            }

            if (primaryType != null && primaryType.Type != KnownPrimaryType.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();
        }
        public void ParseWithServiceClientWithCreateResourceMethod()
        {
            ServiceClient serviceClient = new ServiceClient();

            serviceClient.ApiVersion = "2016-01-01";

            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 = new Method()
            {
                HttpMethod = HttpMethod.Put,
                ReturnType = new Response(responseBody, null),
                Url = url,
            };
            method.Parameters.Add(body);

            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.Equal("http://schema.management.azure.com/schemas/2016-01-01/Mock.Provider.json#", 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", JsonSchema.CreateStringEnum("Mock.Provider/mockResourceNames"), true)
                .AddProperty("apiVersion", JsonSchema.CreateStringEnum("2016-01-01"), true),
                schema.ResourceDefinitions["mockResourceNames"]);
            Assert.NotNull(schema.Definitions);
            Assert.Equal(0, schema.Definitions.Count);
        }
Esempio n. 3
0
 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>();
 }
        private static Property CreateParameterGroupProperty(Parameter 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];
            }

            return groupProperty;
        }
Esempio n. 5
0
        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 = (Core.ClientModel.ParameterLocation)Enum.Parse(typeof(Core.ClientModel.ParameterLocation), unwrappedParameter.In.ToString())
            };
            parameter.IsRequired = parameter.IsRequired || parameter.Location == Core.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;
        }
        private static string GetParameterGroupName(string methodGroupName, string methodName, Parameter parameter)
        {
            if (parameter.Extensions.ContainsKey(SwaggerExtensions.ParameterGroupExtension))
            {
                JContainer extensionObject = parameter.Extensions[SwaggerExtensions.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 = methodGroupName + "-" + methodName + "-" + postfix;
                    }
                    else
                    {
                        parameterGroupName = specifiedGroupName;
                    }
                    return parameterGroupName;
                }
            }

            return null;
        }
Esempio n. 7
0
        /// <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;
                            method.Extensions["nextMethodName"] = nextLinkMethod.Name;
                            method.Extensions["nextMethodGroup"] = nextLinkMethod.Group;
                        }
                    }

                    if (nextLinkMethod == null)
                    {
                        nextLinkMethod = (Method)method.Clone();

                        if (!string.IsNullOrEmpty(pageableExtension.OperationName))
                        {
                            nextLinkMethod.Name = codeNamer.GetMethodName(SwaggerModeler.GetMethodName(
                                new Operation { OperationId = pageableExtension.OperationName }));
                            nextLinkMethod.Group = codeNamer.GetMethodGroupName(SwaggerModeler.GetMethodGroup(
                                new 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);
                                    inputParameter.IsRequired = newGroupingParam.IsRequired;
                                    nextLinkMethod.InputParameterTransformation.ForEach(t => t.ParameterMappings[0].InputParameter = inputParameter);
                                }
                            });

                        serviceClient.Methods.Add(nextLinkMethod);
                    }
                }
            }
        }
 public AzureParameterTemplateModel(Parameter source)
     : base(source)
 {
 }
Esempio n. 9
0
        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 = new PrimaryType(KnownPrimaryType.String)
            });
            flattenedPropertyType.Properties.Add(new Property
            {
                Name = "ProvState",
                Type = new PrimaryType(KnownPrimaryType.String)
            });
            flattenedPropertyType.Properties.Add(new Property
            {
                Name = "Id",
                Type = new PrimaryType(KnownPrimaryType.Int)
            });

            var customObjectPropertyType = new CompositeType();

            customObjectPropertyType.Name = "FooProperty";
            customObjectPropertyType.Properties.Add(new Property
            {
                Name = "Sku",
                Type = new PrimaryType(KnownPrimaryType.String)
            });
            customObjectPropertyType.Properties.Add(new Property
            {
                Name = "ProvState",
                Type = new PrimaryType(KnownPrimaryType.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 = new PrimaryType(KnownPrimaryType.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, SyncMethodsGenerationMode.All);
            var    output   = templateModel.BuildInputMappings();
            string expected =
                @"String paramA = null;
            if (body != null)
            {
                paramA = body.A;
            }
            String paramB = default(String);
            if (body != null)
            {
                paramB = body.B;
            }";

            MultilineAreEqual(expected, output.Trim());
        }
Esempio n. 10
0
        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 = new PrimaryType(KnownPrimaryType.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 outputParameter = new Parameter {
                Name = "body", Type = customObjectType
            };

            serviceClient.Methods.Add(method);
            method.Parameters.Add(new Parameter {
                Name = "paramA", Type = new PrimaryType(KnownPrimaryType.Boolean), SerializedName = "paramA"
            });
            method.Parameters.Add(new Parameter {
                Name = "paramB", Type = new PrimaryType(KnownPrimaryType.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, SyncMethodsGenerationMode.All);
            var output = templateModel.BuildInputMappings();

            System.Console.WriteLine(output);
            string expected =
                @"Foo body = default(Foo);
            if (paramA != null || paramB != null)
            {
                body = new Foo();
                body.A = paramA;
                body.B = paramB;
            }";

            MultilineAreEqual(expected, output.Trim());
        }
        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 = new PrimaryType(KnownPrimaryType.String)
            });
            flattenedPropertyType.Properties.Add(new Property
            {
                Name = "ProvState",
                Type = new PrimaryType(KnownPrimaryType.String)
            });
            flattenedPropertyType.Properties.Add(new Property
            {
                Name = "Id",
                Type = new PrimaryType(KnownPrimaryType.Int)
            });

            var customObjectPropertyType = new CompositeType();
            customObjectPropertyType.Name = "FooProperty";
            customObjectPropertyType.Properties.Add(new Property
            {
                Name = "Sku",
                Type = new PrimaryType(KnownPrimaryType.String)
            });
            customObjectPropertyType.Properties.Add(new Property
            {
                Name = "ProvState",
                Type = new PrimaryType(KnownPrimaryType.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 = new PrimaryType(KnownPrimaryType.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,SyncMethodsGenerationMode.All);
            var output = templateModel.BuildInputMappings();
            string expected =
              @"String paramA = null;
            if (body != null)
            {
                paramA = body.A;
            }
            String paramB = default(String);
            if (body != null)
            {
                paramB = body.B;
            }";

            MultilineAreEqual(expected, output.Trim());
        }
        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 = new PrimaryType(KnownPrimaryType.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 outputParameter = new Parameter { Name = "body", Type = customObjectType };
            serviceClient.Methods.Add(method);
            method.Parameters.Add(new Parameter { Name = "paramA", Type = new PrimaryType(KnownPrimaryType.Boolean), SerializedName = "paramA" });
            method.Parameters.Add(new Parameter { Name = "paramB", Type = new PrimaryType(KnownPrimaryType.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,SyncMethodsGenerationMode.All);
            var output = templateModel.BuildInputMappings();
            System.Console.WriteLine(output);
            string expected =
              @"Foo body = default(Foo);
            if (paramA != null || paramB != null)
            {
                body = new Foo();
                body.A = paramA;
                body.B = paramB;
            }";

            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.
                IEnumerable<ParameterGroup> parameterGroups = ExtractParameterGroups(method);

                List<Parameter> parametersToAddToMethod = new List<Parameter>();
                List<Parameter> parametersToRemoveFromMethod = new List<Parameter>();

                foreach (ParameterGroup parameterGroup in parameterGroups)
                {
                    CompositeType parameterGroupType =
                        generatedParameterGroups.FirstOrDefault(item => item.Name == parameterGroup.Name);

                    if (parameterGroupType == null)
                    {
                        IEnumerable<Method> methodsWhichUseGroup = GetMethodsUsingParameterGroup(serviceClient.Methods, parameterGroup);

                        parameterGroupType = new CompositeType
                        {
                            Name = parameterGroup.Name,
                            Documentation = GenerateParameterGroupModelText(methodsWhichUseGroup)
                        };
                        generatedParameterGroups.Add(parameterGroupType);

                        //Add to the service client
                        serviceClient.ModelTypes.Add(parameterGroupType);
                    }

                    foreach (Property property in parameterGroup.ParameterMapping.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 newParameter = new Parameter()
                    {
                        Name = parameterGroup.Name,
                        IsRequired = isGroupParameterRequired,
                        Location = ParameterLocation.None,
                        SerializedName = string.Empty,
                        Type = parameterGroupType,
                        Documentation = "Additional parameters for the operation"
                    };
                    parametersToAddToMethod.Add(newParameter);

                    //Link the grouped parameters to their parent, and remove them from the method parameters
                    foreach (Property property in parameterGroup.ParameterMapping.Keys)
                    {
                        Parameter p = parameterGroup.ParameterMapping[property];

                        var parameterTransformation = new ParameterTransformation
                        {
                            OutputParameter = p
                        };

                        parameterTransformation.ParameterMappings.Add(new ParameterMapping
                        {
                            InputParameter = newParameter,
                            InputParameterProperty = property.GetClientName()
                        });
                        method.InputParameterTransformation.Add(parameterTransformation);
                        parametersToRemoveFromMethod.Add(p);
                    }
                }

                method.Parameters.RemoveAll(p => parametersToRemoveFromMethod.Contains(p));
                method.Parameters.AddRange(parametersToAddToMethod);

                // Copy back flattening transformations if any
                flatteningTransformations.ForEach(t => method.InputParameterTransformation.Add(t));
            }
        }
Esempio n. 14
0
        public static string GetParameterDocumentationType(Parameter parameter)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }
            string typeName = "object";
            if (parameter.Type is PrimaryType)
            {
                typeName = parameter.Type.Name;
            }
            else if (parameter.Type is SequenceType)
            {
                typeName = "array";
            }
            else if (parameter.Type is EnumType)
            {
                typeName = "string";
            }

            return typeName.ToLower(CultureInfo.InvariantCulture);
        }
 public ParameterTemplateModel(Parameter source)
 {
     this.LoadFrom(source);
 }
Esempio n. 16
0
 /// <summary>
 /// Performs a deep clone of a parameter.
 /// </summary>
 /// <returns>A deep clone of current object.</returns>
 public object Clone()
 {
     Parameter param = new Parameter();
     param.LoadFrom(this);
     return param;
 }
Esempio n. 17
0
        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));
        }
Esempio n. 18
0
        /// <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;
        }
Esempio n. 19
0
 /// <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);
     }
 }
Esempio n. 20
0
        /// <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 == 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);

                            var documentationString = !string.IsNullOrEmpty(property.Summary) ? property.Summary + " " : string.Empty;
                            documentationString += property.Documentation;
                            newMethodParameter.Documentation = documentationString;

                            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);
                    }
                }
            }
        }
Esempio n. 21
0
        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);
        }
Esempio n. 22
0
        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, "Microsoft.Rest.Azure.OData.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);
                }
            }
        }