예제 #1
0
        public MethodTemplateModel(Method source, string owner, string packageName, MethodScopeProvider methodScope)
        {
            this.LoadFrom(source);

            MethodScope = methodScope;
            Owner = owner;
            PackageName = packageName;

            var parameter = Parameters.Find(p => p.Type.IsPrimaryType(KnownPrimaryType.Stream)
                                                && !(p.Location == ParameterLocation.Body || p.Location == ParameterLocation.FormData));
            if (parameter != null)
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
                    Resources.IllegalStreamingParameter, parameter.Name));
            }

            if (string.IsNullOrEmpty(Description))
            {
                Description = string.Format("sends the {0} request.", ScopedName.ToPhrase());
            }

            if (this.IsLongRunningOperation())
            {
                Description += lroDescription;
            }
        }
예제 #2
0
 public MethodTemplateModel(Method source, ServiceClient serviceClient)
 {
     this.LoadFrom(source);
     ParameterTemplateModels = new List<ParameterTemplateModel>();
     source.Parameters.ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));
     ServiceClient = serviceClient;
     if (source.Group != null)
     {
         OperationName = source.Group.ToPascalCase();
     }
     else
     {
         OperationName = serviceClient.Name;
     }
     AddCustomHeader = true;
     string formatter;
     foreach (var parameter in LocalParameters)
     {
         if (string.IsNullOrWhiteSpace(parameter.DefaultValue))
         {
             parameter.DefaultValue = PythonConstants.None;
         }
     }
     foreach (Match m in Regex.Matches(Url, @"\{[\w]+:[\w]+\}"))
     {
         formatter = m.Value.Split(':').First() + '}';
         Url = Url.Replace(m.Value, formatter);
     }
 }
        public static StringBuilder OnBuildMethodParameter(Method method,
            SwaggerParameter currentSwaggerParam,
            StringBuilder paramNameBuilder)
        {
            if (currentSwaggerParam == null)
            {
                throw new ArgumentNullException("currentSwaggerParam");
            }

            bool hasCollectionFormat = currentSwaggerParam.CollectionFormat != CollectionFormat.None;

            if (currentSwaggerParam.Type == DataType.Array && !hasCollectionFormat)
            {
                // If the parameter type is array default the collectionFormat to csv
                currentSwaggerParam.CollectionFormat = CollectionFormat.Csv;
            }

            if (hasCollectionFormat)
            {
                AddCollectionFormat(currentSwaggerParam, paramNameBuilder);
                if (currentSwaggerParam.In == ParameterLocation.Path)
                {
                    if (method == null || method.Url == null)
                    {
                       throw new ArgumentNullException("method");
                    }

                    method.Url = method.Url.Replace(
                        string.Format(CultureInfo.InvariantCulture, "{0}", currentSwaggerParam.Name),
                        string.Format(CultureInfo.InvariantCulture, "{0}", paramNameBuilder));
                }
            }
            return paramNameBuilder;
        }
        private static ParameterGroup BuildParameterGroup(string parameterGroupName, Method method)
        {
            Dictionary<Property, Parameter> parameterMapping = method.Parameters.Where(
                p => GetParameterGroupName(method.Group, method.Name, p) == parameterGroupName).ToDictionary(
                    CreateParameterGroupProperty,
                    p => p);

            return new ParameterGroup(parameterGroupName, parameterMapping);
        }
예제 #5
0
        /// <summary>
        /// Initializes a new instance of the class MethodTemplateModel.
        /// </summary>
        /// <param name="source">The source object.</param>
        /// <param name="serviceClient">The service client.</param>
        public MethodTemplateModel(Method source, ServiceClient serviceClient)
        {
            this.LoadFrom(source);
            ParameterTemplateModels = new List<ParameterTemplateModel>();
            source.Parameters.ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));

            LogicalParameterTemplateModels = new List<ParameterTemplateModel>();
            source.LogicalParameters.ForEach(p => LogicalParameterTemplateModels.Add(new ParameterTemplateModel(p)));

            ServiceClient = serviceClient;
        }
        public AzureMethodTemplateModel(Method source, ServiceClient serviceClient)
            : base(source, serviceClient)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source);
            this.RequestIdString = AzureExtensions.GetRequestIdString(source);
        }
예제 #7
0
 public MethodTemplateModel(Method source, ServiceClient serviceClient, SyncMethodsGenerationMode syncWrappers)
 {
     this.LoadFrom(source);
     SyncMethods = syncWrappers;
     ParameterTemplateModels = new List<ParameterTemplateModel>();
     LogicalParameterTemplateModels = new List<ParameterTemplateModel>();
     source.Parameters.ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));
     source.LogicalParameters.ForEach(p => LogicalParameterTemplateModels.Add(new ParameterTemplateModel(p)));
     ServiceClient = serviceClient;
     MethodGroupName = source.Group ?? serviceClient.Name;
     this.IsCustomBaseUri = serviceClient.Extensions.ContainsKey(SwaggerExtensions.ParameterizedHostExtension);
 }
        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);
        }
        /// <summary>
        /// Initializes a new instance of the AzureMethodTemplateModel class.
        /// </summary>
        /// <param name="source">The method current model is built for.</param>
        /// <param name="serviceClient">The service client - main point of access to the SDK.</param>
        public AzureMethodTemplateModel(Method source, ServiceClient serviceClient)
            : base(source, serviceClient)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            ParameterTemplateModels.Clear();
            source.Parameters.ForEach(p => ParameterTemplateModels.Add(new AzureParameterTemplateModel(p)));

            this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source);
            this.RequestIdString = AzureExtensions.GetRequestIdString(source);
        }
예제 #10
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>();
 }
예제 #11
0
        public MethodTemplateModel(Method source, ServiceClient serviceClient)
        {
            this.LoadFrom(source);
            ParameterTemplateModels = new List<ParameterTemplateModel>();
            GroupedParameterTemplateModels = new List<ParameterTemplateModel>();
            source.Parameters.ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));

            ServiceClient = serviceClient;
            if (source.Group != null)
            {
                OperationName = source.Group.ToPascalCase();
            }
            else
            {
                OperationName = serviceClient.Name;
            }

            BuildOptionsParameterTemplateModel();
        }
        public AzureMethodTemplateModel(Method source, ServiceClient serviceClient, SyncMethodsGenerationMode syncWrappers)
            : base(source, serviceClient, syncWrappers)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            ParameterTemplateModels.Clear();
            LogicalParameterTemplateModels.Clear();
            source.Parameters.ForEach(p => ParameterTemplateModels.Add(new AzureParameterTemplateModel(p)));
            source.LogicalParameters.ForEach(p => LogicalParameterTemplateModels.Add(new AzureParameterTemplateModel(p)));
            if (MethodGroupName != ServiceClient.Name)
            {
                MethodGroupName = MethodGroupName + "Operations";
            }

            this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source);
            this.RequestIdString = AzureExtensions.GetRequestIdString(source);
        }
예제 #13
0
        public AzureMethodTemplateModel(Method source, ServiceClient serviceClient)
            : base(source, serviceClient)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source);
            this.RequestIdString = AzureExtensions.GetRequestIdString(source);
            _namer = new AzureJavaCodeNamer(serviceClient.Namespace);
            _returnTypeModel = new AzureResponseModel(ReturnType, this);
            _responseModels = new Dictionary<HttpStatusCode, ResponseModel>();
            Responses.ForEach(r => _responseModels.Add(r.Key, new AzureResponseModel(r.Value, this)));

            if (this.IsPagingOperation || this.IsPagingNextOperation)
            {
                var ext = this.Extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer;
                pageClassName = (string)ext["className"] ?? "PageImpl";
            }
        }
예제 #14
0
 public MethodTemplateModel(Method source, ServiceClient serviceClient)
 {
     this.LoadFrom(source);
     ParameterModels = new List<ParameterModel>();
     LogicalParameterModels = new List<ParameterModel>();
     source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this)));
     source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this)));
     source.LogicalParameters.ForEach(p => LogicalParameterModels.Add(new ParameterModel(p, this)));
     ServiceClient = serviceClient;
     if (source.Group != null)
     {
         OperationName = source.Group.ToPascalCase();
         ClientReference = "this.client";
     }
     else
     {
         OperationName = serviceClient.Name;
         ClientReference = "this";
     }
     _returnTypeModel = new ResponseModel(ReturnType);
     _responseModels = new Dictionary<HttpStatusCode,ResponseModel>();
     Responses.ForEach(r => _responseModels.Add(r.Key, new ResponseModel(r.Value)));
 }
예제 #15
0
        /// <summary>
        /// Normalizes the parameter names of a method
        /// </summary>
        /// <param name="method"></param>
        protected override void NormalizeParameters(Method method)
        {
            if (method != null)
            {
                foreach (var parameter in method.Parameters)
                {
                    parameter.Name = method.Scope.GetUniqueName(GetParameterName(parameter.GetClientName()));
                    parameter.Type = NormalizeTypeReference(parameter.Type);
                    QuoteParameter(parameter);
                }

                foreach (var parameterTransformation in method.InputParameterTransformation)
                {
                    parameterTransformation.OutputParameter.Name = method.Scope.GetUniqueName(GetParameterName(parameterTransformation.OutputParameter.GetClientName()));
                    parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type);

                    QuoteParameter(parameterTransformation.OutputParameter);

                    foreach (var parameterMapping in parameterTransformation.ParameterMappings)
                    {
                        if (parameterMapping.InputParameterProperty != null)
                        {
                            parameterMapping.InputParameterProperty = GetPropertyName(parameterMapping.InputParameterProperty);
                        }

                        if (parameterMapping.OutputParameterProperty != null)
                        {
                            parameterMapping.OutputParameterProperty = GetPropertyName(parameterMapping.OutputParameterProperty);
                        }
                    }
                }
            }
        }
예제 #16
0
        private List<Stack<IType>> BuildResponses(Method method, CompositeType headerType)
        {
            string methodName = method.Name;
            var typesList = new List<Stack<IType>>();
            foreach (var response in _operation.Responses)
            {
                if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase))
                {
                    TryBuildDefaultResponse(methodName, response.Value, method, headerType);
                }
                else
                {
                    if (
                        !(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
                            typesList, headerType) ||
                          TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
                          TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
                              typesList, headerType)))
                    {
                        throw new InvalidOperationException(
                            string.Format(CultureInfo.InvariantCulture,
                            Resources.UnsupportedMimeTypeForResponseBody,
                            methodName,
                            response.Key));
                    }
                }
            }

            return typesList;
        }
예제 #17
0
 private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IType headerType)
 {
     IType errorModel = null;
     if (SwaggerOperationProducesJson())
     {
         if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
         {
             method.DefaultResponse = new Response(errorModel, headerType);
         }
     }
 }
 public AzureFluentMethodTemplateModel(Method source, ServiceClient serviceClient)
     : base(source, serviceClient)
 {
     _namer = new AzureJavaFluentCodeNamer(serviceClient.Namespace);
 }
예제 #19
0
 public string DefaultValue(Method method)
 {
     return "null";
 }
예제 #20
0
        private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
        {
            bool handled = false;

            if (response.Schema == null)
            {
                method.Responses[responseStatusCode] = new Response(null, headerType);
                handled = true;
            }
            else
            {
                if (_operation.Produces.IsNullOrEmpty())
                {
                    method.Responses[responseStatusCode] = new Response(new PrimaryType(KnownPrimaryType.Object), headerType);
                    BuildMethodReturnTypeStack(new PrimaryType(KnownPrimaryType.Object), types);
                    handled = true;
                }

                var unwrapedSchemaProperties =
                    _swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
                if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
                {
                    Logger.LogWarning(Resources.NoProduceOperationWithBody,
                        methodName);
                }
            }

            return handled;
        }
예제 #21
0
        public static string GetRequestIdString(Method method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            string requestIdName = "x-ms-request-id";
            if (method.Extensions.ContainsKey(RequestIdExtension))
            {
                string extensionObject = method.Extensions[RequestIdExtension] as string;
                if (extensionObject != null)
                {
                    requestIdName = extensionObject;
                }
            }
            
            return requestIdName;
        }        
        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());
        }
예제 #23
0
        private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
        {
            bool handled = false;
            IType serviceType;
            if (SwaggerOperationProducesJson())
            {
                if (TryBuildResponseBody(methodName, response,
                    s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
                {
                    method.Responses[responseStatusCode] = new Response(serviceType, headerType);
                    BuildMethodReturnTypeStack(serviceType, types);
                    handled = true;
                }
            }

            return handled;
        }
        /// <summary>
        /// Gets Get method invocation arguments for Long Running Operations.
        /// </summary>
        /// <param name="getMethod">Get method.</param>
        /// <returns>Invocation arguments.</returns>
        public string GetMethodInvocationArgs(Method getMethod)
        {
            if (getMethod == null)
            {
                throw new ArgumentNullException("getMethod");
            }

            var invocationParams = new List<string>();
            getMethod.Parameters
                .Where(p => LocalParameters.Any(lp => lp.Name == p.Name))
                .ForEach(p => invocationParams.Add(string.Format(CultureInfo.InvariantCulture,"{0}: {0}", p.Name)));
            invocationParams.Add("customHeaders: customHeaders");
            invocationParams.Add("cancellationToken: cancellationToken");
            return string.Join(", ", invocationParams);
        }
예제 #25
0
        private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
            Method method, List<Stack<IType>> types, IType headerType)
        {
            bool handled = false;
            if (SwaggerOperationProducesNotEmpty())
            {
                if (response.Schema != null)
                {
                    IType serviceType = response.Schema.GetBuilder(_swaggerModeler)
                        .BuildServiceType(response.Schema.Reference.StripDefinitionPath());

                    Debug.Assert(serviceType != null);

                    BuildMethodReturnTypeStack(serviceType, types);

                    var compositeType = serviceType as CompositeType;
                    if (compositeType != null)
                    {
                        VerifyFirstPropertyIsByteArray(compositeType);
                    }
                    method.Responses[responseStatusCode] = new Response(serviceType, headerType);
                    handled = true;
                }
            }
            return handled;
        }
예제 #26
0
        public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
        {
            EnsureUniqueMethodName(methodName, methodGroup);

            var method = new Method
            {
                HttpMethod = httpMethod,
                Url = url,
                Name = methodName,
                SerializedName = _operation.OperationId
            };

            method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
            string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
            if (!string.IsNullOrEmpty(produce))
            {
                method.RequestContentType = produce;
            }

            if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
                method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
            {
                // Enable UTF-8 charset
                method.RequestContentType += "; charset=utf-8";
            }

            method.Description = _operation.Description;
            method.Summary = _operation.Summary;
            method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
            method.Deprecated = _operation.Deprecated;

            // Service parameters
            if (_operation.Parameters != null)
            {
                BuildMethodParameters(method);
            }

            // Build header object
            var responseHeaders = new Dictionary<string, Header>();
            foreach (var response in _operation.Responses.Values)
            {
                if (response.Headers != null)
                {
                    response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
                }
            }

            var headerTypeName = string.Format(CultureInfo.InvariantCulture,
                "{0}-{1}-Headers", methodGroup, methodName).Trim('-');
            var headerType = new CompositeType
            {
                Name = headerTypeName,
                SerializedName = headerTypeName,
                Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
            };
            responseHeaders.ForEach(h =>
            {
                var property = new Property
                {
                    Name = h.Key,
                    SerializedName = h.Key,
                    Type = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
                    Documentation = h.Value.Description
                };
                headerType.Properties.Add(property);
            });

            if (!headerType.Properties.Any())
            {
                headerType = null;
            }

            // Response format
            List<Stack<IType>> typesList = BuildResponses(method, headerType);

            method.ReturnType = BuildMethodReturnType(typesList, headerType);
            if (method.Responses.Count == 0)
            {
                method.ReturnType = method.DefaultResponse;
            }

            if (method.ReturnType.Headers != null)
            {
                _swaggerModeler.ServiceClient.HeaderTypes.Add(method.ReturnType.Headers as CompositeType);
            }

            // Copy extensions
            _operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));

            return method;
        }
예제 #27
0
        private static Parameter CreateParameterFromGrouping(IEnumerable<ParameterTransformation> grouping, Method method, ServiceClient serviceClient)
        {
            var properties = new List<Property>();
            string parameterGroupName = null;
            foreach (var parameter in grouping.Select(g => g.OutputParameter))
            {
                Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as Newtonsoft.Json.Linq.JContainer;
                string specifiedGroupName = extensionObject.Value<string>("name");
                if (specifiedGroupName == null)
                {
                    string postfix = extensionObject.Value<string>("postfix") ?? "Parameters";
                    parameterGroupName = method.Group + "-" + method.Name + "-" + postfix;
                }
                else
                {
                    parameterGroupName = specifiedGroupName;
                }

                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
                };
                properties.Add(groupProperty);
            }
            
            var parameterGroupType = new CompositeType()
            {
                Name = parameterGroupName,
                Documentation = "Additional parameters for the " + method.Name + " operation."
            };

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

            foreach (Property property in properties)
            {
                parameterGroupType.Properties.Add(property);
            }

            bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired);

            //Create the new parameter object based on the parameter group type
            return new Parameter()
            {
                Name = parameterGroupName,
                IsRequired = isGroupParameterRequired,
                Location = ParameterLocation.None,
                SerializedName = string.Empty,
                Type = parameterGroupType,
                Documentation = "Additional parameters for the operation"
            };
        }
        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());
        }
예제 #29
0
        private static string[] ParseResourceTypes(string resourceProvider, string methodUrlPathAfterProvider, Method method)
        {
            // Gather the list of resource types defined by this method url. Usually this will
            // result in only one resource type, but if the method url contains an enumerated
            // resource type parameter, then multiple resource types could be declared from a
            // single method url.
            List<string> resourceTypes = new List<string>();
            resourceTypes.Add(resourceProvider);
            string[] pathSegments = methodUrlPathAfterProvider.Split(new char[] { '/' });
            for (int i = 0; i < pathSegments.Length; i += 2)
            {
                string pathSegment = pathSegments[i];
                if (IsPathVariable(pathSegment))
                {
                    string parameterName = pathSegment.Substring(1, pathSegment.Length - 2);
                    Parameter parameter = method.Parameters.FirstOrDefault(methodParameter => methodParameter.Name == parameterName);
                    if (parameter == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Found undefined parameter reference {0} in create resource method \"{1}/{2}/{3}\".", pathSegment, resourceMethodPrefix, resourceProvider, methodUrlPathAfterProvider));
                    }

                    if (parameter.Type == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Parameter reference {0} has no defined type.", pathSegment));
                    }

                    EnumType parameterType = parameter.Type as EnumType;
                    if (parameterType == null)
                    {
                        // If we encounter a parameter in the URL that isn't an enumeration, then
                        // we can't create a resource from this URL.
                        resourceTypes.Clear();
                        break;
                    }

                    if (parameterType.Values == null || parameterType.Values.Count == 0)
                    {
                        string errorMessage = string.Format(CultureInfo.CurrentCulture, "Parameter reference {0} is defined as an enum type, but it doesn't have any specified values.", pathSegment);
                        throw new ArgumentException(errorMessage);
                    }

                    List<string> newResourceTypes = new List<string>();
                    foreach (string resourceType in resourceTypes)
                    {
                        foreach (EnumValue parameterValue in parameterType.Values)
                        {
                            newResourceTypes.Add(string.Join("/", resourceType, parameterValue.Name));
                        }
                    }

                    resourceTypes = newResourceTypes;
                }
                else
                {
                    for (int j = 0; j < resourceTypes.Count; ++j)
                    {
                        resourceTypes[j] = string.Join("/", resourceTypes[j], pathSegment);
                    }
                }
            }

            return resourceTypes.ToArray();
        }
예제 #30
0
        public static string GetClientRequestIdString(Method method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (method.Extensions.ContainsKey(ClientRequestIdExtension))
            {
                return method.Extensions[ClientRequestIdExtension] as string;
            }
            else
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Method missing expected {0} extension", ClientRequestIdExtension));
            }
        }