Esempio n. 1
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)));
     ServiceClient = serviceClient;
 }
        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;
        }
Esempio n. 3
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 MethodTemplateModel(Method source, ServiceClient serviceClient)
 {
     this.LoadFrom(source);
     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;
 }
        /// <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)));
        }
 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);
 }
Esempio n. 7
0
 public MethodTemplateModel(Method source, ServiceClient serviceClient)
 {
     this.LoadFrom(source);
     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(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension);
 }
        /// <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);
        }
        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);
            _returnTypeModel = new AzureResponseModel(ReturnType, this);
            _responseModels = new Dictionary<HttpStatusCode, ResponseModel>();
            Responses.ForEach(r => _responseModels.Add(r.Key, new AzureResponseModel(r.Value, this)));
        }
 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;
     }
 }
Esempio n. 11
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>();
 }
Esempio n. 12
0
 public MethodTemplateModel(Method source, ServiceClient serviceClient)
 {
     this.LoadFrom(source);
     ParameterTemplateModels = new List<ParameterTemplateModel>();
     source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));
     source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p)));
     ServiceClient = serviceClient;
     if (source.Group != null)
     {
         OperationName = source.Group.ToPascalCase();
         ClientReference = "client";
     }
     else
     {
         OperationName = serviceClient.Name;
         ClientReference = "";
     }
 }
Esempio n. 13
0
        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);
        }
Esempio n. 14
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);
            _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";
            }
        }
Esempio n. 15
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)));
 }
Esempio n. 16
0
 public string DefaultValue(Method method)
 {
     if (this.Name == "byte[]")
     {
         return "new byte[0]";
     }
     else if (this.Name == "Byte[]")
     {
         return "new Byte[0]";
     }
     else if (this.Name == "RequestBody")
     {
         return "RequestBody.create(MediaType.parse(\"" + method.RequestContentType + "\"), new byte[0])";
     }
     else if (this.IsInstanceType)
     // instance type
     {
         return "null";
     }
     else
     {
         throw new NotSupportedException(this.Name + " does not have default value!");
     }
 }
Esempio n. 17
0
 /// <summary>
 /// Performs a deep clone of a method.
 /// </summary>
 /// <returns></returns>
 public object Clone()
 {
     Method newMethod = new Method();
     newMethod.LoadFrom(this);
     newMethod.Extensions = new Dictionary<string, object>();
     newMethod.Parameters = new List<Parameter>();
     newMethod.RequestHeaders = new Dictionary<string, string>();
     newMethod.Responses = new Dictionary<HttpStatusCode, Response>();
     newMethod.InputParameterTransformation = new List<ParameterTransformation>();
     newMethod.Scope = new ScopeProvider();
     this.Extensions.ForEach(e => newMethod.Extensions[e.Key] = e.Value);
     this.Parameters.ForEach(p => newMethod.Parameters.Add((Parameter)p.Clone()));
     this.InputParameterTransformation.ForEach(m => newMethod.InputParameterTransformation.Add((ParameterTransformation)m.Clone()));
     this.RequestHeaders.ForEach(r => newMethod.RequestHeaders[r.Key] = r.Value);
     this.Responses.ForEach(r => newMethod.Responses[r.Key] = r.Value);
     return newMethod;
 }
        public void ResourceIsFlattenedForConflictingResource()
        {
            var serviceClient = new ServiceClient();
            serviceClient.BaseUrl = "https://petstore.swagger.wordnik.com";
            serviceClient.ApiVersion = "1.0.0";
            serviceClient.Documentation =
                "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification";
            serviceClient.Name = "Swagger Petstore";

            var getPet = new Method();
            var resource = new CompositeType();
            var dogProperties = new CompositeType();
            var dog = new CompositeType();
            serviceClient.Methods.Add(getPet);
            resource.Name = "resource";
            resource.Extensions[AzureExtensions.AzureResourceExtension] = true;
            resource.Properties.Add(new Property
            {
                Name = "id",
                Type = PrimaryType.String,
                IsRequired = true
            });
            resource.Properties.Add(new Property
            {
                Name = "location",
                Type = PrimaryType.String,
                IsRequired = true
            });
            resource.Properties.Add(new Property
            {
                Name = "name",
                Type = PrimaryType.String,
                IsRequired = true
            });
            resource.Properties.Add(new Property
            {
                Name = "tags",
                Type = new SequenceType { ElementType = PrimaryType.String },
                IsRequired = true
            });
            resource.Properties.Add(new Property
            {
                Name = "type",
                Type = PrimaryType.String,
                IsRequired = true
            });
            dogProperties.Name = "dogProperties";
            dogProperties.Properties.Add(new Property
            {
                Name = "id",
                Type = PrimaryType.Long,
                IsRequired = true
            });
            dogProperties.Properties.Add(new Property
            {
                Name = "name",
                Type = PrimaryType.String,
                IsRequired = true
            });
            dog.Name = "dog";
            dog.BaseModelType = resource;
            dog.Properties.Add(new Property
            {
                Name = "properties",
                Type = dogProperties,
                IsRequired = true
            });
            dog.Properties.Add(new Property
            {
                Name = "pedigree",
                Type = PrimaryType.Boolean,
                IsRequired = true
            });
            getPet.ReturnType = new Response(dog, null);

            serviceClient.ModelTypes.Add(resource);
            serviceClient.ModelTypes.Add(dogProperties);
            serviceClient.ModelTypes.Add(dog);

            var codeGen = new SampleAzureCodeGenerator(new Settings());
            codeGen.NormalizeClientModel(serviceClient);
            Assert.Equal(3, serviceClient.ModelTypes.Count);
            Assert.Equal("dog", serviceClient.ModelTypes.First(m => m.Name == "dog").Name);
            Assert.Equal(3, serviceClient.ModelTypes.First(m => m.Name == "dog").Properties.Count);
            Assert.True(serviceClient.ModelTypes.First(m => m.Name == "dog").Properties.Any(p => p.Name == "dogName"));
            Assert.True(serviceClient.ModelTypes.First(m => m.Name == "dog").Properties.Any(p => p.Name == "dogId"));
            Assert.True(serviceClient.ModelTypes.First(m => m.Name == "dog").Properties.Any(p => p.Name == "pedigree"));
            Assert.Equal("dog", serviceClient.Methods[0].ReturnType.Body.Name);
            Assert.Equal(serviceClient.ModelTypes.First(m => m.Name == "dog"), serviceClient.Methods[0].ReturnType.Body);
        }
Esempio n. 19
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;

            // Service parameters
            if (_operation.Parameters != null)
            {
                foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
                {
                    var parameter = ((ParameterBuilder) swaggerParameter.GetBuilder(_swaggerModeler)).Build();
                    method.Parameters.Add(parameter);

                    StringBuilder parameterName = new StringBuilder(parameter.Name);
                    parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
                        parameterName);

                    if (swaggerParameter.In == ParameterLocation.Header)
                    {
                        method.RequestHeaders[swaggerParameter.Name] =
                            string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
                    }
                }
            }

            // 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
            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));
                    }
                }
            }

            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;
        }
Esempio n. 20
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);
         }
     }
 }
Esempio n. 21
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;
        }
Esempio n. 22
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;
        }
Esempio n. 23
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;
        }
Esempio n. 24
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;
        }        
Esempio n. 25
0
 public static string GetClientRequestIdString(Method method)
 {
     if (method == null)
     {
         throw new ArgumentNullException("method");
     }
     
     string clientRequestIdName = "x-ms-client-request-id";
     foreach (Parameter parameter in method.Parameters)
     {
         if (parameter.Extensions.ContainsKey(ClientRequestIdExtension))
         {
             bool? extensionObject = parameter.Extensions[ClientRequestIdExtension] as bool?;
             if (extensionObject != null)
             {
                 bool useParamAsClientRequestId = extensionObject.Value;
                 if (useParamAsClientRequestId)
                 {
                     //TODO: Need to do something if they specify two ClientRequestIdExtensions for the same method...?
                     clientRequestIdName = parameter.SerializedName;
                     break;
                 }
             }
         }
     }
     
     return clientRequestIdName;
 }
Esempio n. 26
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));
            }
        }
 public AzureMethodTemplateModel(Method source, ServiceClient serviceClient)
     : base(source, serviceClient)
 {
 }
Esempio n. 28
0
        /// <summary>
        /// Normalizes names in the method
        /// </summary>
        /// <param name="method"></param>
        public virtual void NormalizeMethod(Method method)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }
            method.Name = GetMethodName(method.Name);
            method.Group = GetMethodGroupName(method.Group);
            method.ReturnType = NormalizeTypeReference(method.ReturnType);
            method.DefaultResponse = NormalizeTypeReference(method.DefaultResponse);
            var normalizedResponses = new Dictionary<HttpStatusCode, Response>();
            foreach (var statusCode in method.Responses.Keys)
            {
                normalizedResponses[statusCode] = NormalizeTypeReference(method.Responses[statusCode]);
            }

            method.Responses.Clear();
            foreach (var statusCode in normalizedResponses.Keys)
            {
                method.Responses[statusCode] = normalizedResponses[statusCode];
            }
            foreach (var parameter in method.Parameters)
            {
                parameter.Name = GetParameterName(parameter.Name);
                parameter.Type = NormalizeTypeReference(parameter.Type);
            }

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

                foreach (var parameterMapping in parameterTransformation.ParameterMappings)
                {
                    if (parameterMapping.InputParameterProperty != null)
                    {
                        parameterMapping.InputParameterProperty = string.Join(".",
                            parameterMapping.InputParameterProperty.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(p => GetPropertyName(p)));
                    }

                    if (parameterMapping.OutputParameterProperty != null)
                    {
                        parameterMapping.OutputParameterProperty = string.Join(".",
                            parameterMapping.OutputParameterProperty.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(p => GetPropertyName(p)));
                    }
                }
            }
        }
Esempio n. 29
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);
                        }
                    }
                }
            }
        }
Esempio n. 30
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"
            };
        }