Пример #1
0
        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 = ((string)method.Url).Replace(
                        string.Format(CultureInfo.InvariantCulture, "{0}", currentSwaggerParam.Name),
                        string.Format(CultureInfo.InvariantCulture, "{0}", paramNameBuilder));
                }
            }
            return paramNameBuilder;
        }
Пример #2
0
 public virtual Method Add(Method method)
 {
     if (method.Group.IsNullOrEmpty())
     {
         method.Group.Value = string.Empty;
     }
     // methods are delegated to the method group of their choice. 
     return GetOrAddMethodGroup(method.Group).Add(method);
 }
        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);
        }
        private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType 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;
        }
        private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
            OperationResponse response, Method method, List<Stack<IModelType>> types, IModelType headerType)
        {
            bool handled = false;
            IModelType 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;
        }
        private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
            Method method, List<Stack<IModelType>> types, IModelType headerType)
        {
            bool handled = false;
            if (SwaggerOperationProducesNotEmpty())
            {
                if (response.Schema != null)
                {
                    IModelType 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;
        }
        private List<Stack<IModelType>> BuildResponses(Method method, CompositeType headerType)
        {
            string methodName = method.Name;
            var typesList = new List<Stack<IModelType>>();
            foreach (var response in _operation.Responses)
            {
                if (response.Key.EqualsIgnoreCase("default"))
                {
                    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;
        }
        private void BuildMethodParameters(Method method)
        {
            foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
            {
                var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
                method.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);
                }
            }
        }
Пример #9
0
 public virtual void Remove(Method item)
 {
     _methods.Remove(item);
 }
Пример #10
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;
        }        
Пример #11
0
        private static Parameter CreateParameterFromGrouping(IEnumerable<ParameterTransformation> grouping, Method method, CodeModel codeModel)
        {
            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>(new
                {
                    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,
                    ModelType = parameter.ModelType,
                    SerializedName = default(string) //Parameter is never serialized directly
                });
                properties.Add(groupProperty);
            }
            
            var parameterGroupType = New <CompositeType>(parameterGroupName, new
            {
                Documentation = "Additional parameters for the " + method.Name + " operation."
            });

            //Add to the service client
            codeModel.Add(parameterGroupType);

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

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

            //Create the new parameter object based on the parameter group type
            return New<Parameter>(new
            {
                Name = parameterGroupName,
                IsRequired = isGroupParameterRequired,
                Location = ParameterLocation.None,
                SerializedName = string.Empty,
                ModelType = parameterGroupType,
                Documentation = "Additional parameters for the operation"
            });
        }
Пример #12
0
        /// <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);
        }
        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.RawValue == 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.ModelType == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Parameter reference {0} has no defined type.", pathSegment));
                    }

                    EnumType parameterType = parameter.ModelType 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();
        }
Пример #14
0
 public override Method Add(Method method)
 {
     (method as MethodCs).SyncMethods = Singleton<GeneratorSettingsCs>.Instance.SyncMethods;
     return base.Add(method);
 }
        private static IEnumerable<ParameterGroup> ExtractParameterGroups(Method method)
        {
            IEnumerable<string> parameterGroupNames = ExtractParameterGroupNames(method);

            return parameterGroupNames.Select(parameterGroupName => BuildParameterGroup(parameterGroupName, method));
        }
 private static IEnumerable<string> ExtractParameterGroupNames(Method method)
 {
     return method.Parameters.Select(p => GetParameterGroupName(method.Group, method.Name, p)).Where(name => !string.IsNullOrEmpty(name)).Distinct();
 }
 private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IModelType headerType)
 {
     IModelType errorModel = null;
     if (SwaggerOperationProducesJson())
     {
         if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
         {
             method.DefaultResponse = new Response(errorModel, headerType);
         }
     }
 }
Пример #18
0
 public virtual Method Insert(Method item)
 {
     if( !_methods.Contains(item))
     {
         // disambiguation is performed when the item's parent reference is changed
         item.MethodGroup = this;
         _methods.Insert(0, item);
     }
     return item;
 }
Пример #19
0
 partial void BeforeAdd(Method item);
Пример #20
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));
            }
        }