private IEnumerable<CompositeType> GetDependencyTypes(CompositeType type) { List<CompositeType> result = new List<CompositeType>() { type.BaseModelType }; return result; }
public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { this.LoadFrom(source); ServiceClient = serviceClient; if(source.BaseModelType != null) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } }
public ModelTemplateModel(CompositeType source) { this.LoadFrom(source); PropertyTemplateModels = new List<PropertyTemplateModel>(); source.Properties.ForEach(p => PropertyTemplateModels.Add(new PropertyTemplateModel(p))); if (source.BaseModelType != null) { this._baseModel = new ModelTemplateModel(source.BaseModelType); } }
/// <summary> /// Initializes a new instance of the ModelTemplateModel class. /// </summary> /// <param name="source">The object to create model from.</param> /// <param name="serviceClient">The service client.</param> public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { this.LoadFrom(source); PropertyTemplateModels = new List<PropertyTemplateModel>(); source.Properties.ForEach(p => PropertyTemplateModels.Add(new PropertyTemplateModel(p))); if (source.BaseModelType != null) { parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } }
public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { this.LoadFrom(source); ServiceClient = serviceClient; if(source.BaseModelType != null) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } _namer = new JavaCodeNamer(serviceClient.Namespace); PropertyModels = new List<PropertyModel>(); Properties.ForEach(p => PropertyModels.Add(new PropertyModel(p, serviceClient.Namespace))); }
private void BuildOptionsParameterTemplateModel() { CompositeType optionsType; optionsType = new CompositeType { Name = "options", SerializedName = "options", Documentation = "Optional Parameters." }; var optionsParmeter = new Parameter { Name = "options", SerializedName = "options", IsRequired = false, Documentation = "Optional Parameters.", Location = ParameterLocation.None, Type = optionsType }; IEnumerable<ParameterTemplateModel> optionalParameters = LocalParameters.Where(p => !p.IsRequired); foreach (ParameterTemplateModel parameter in optionalParameters) { Property optionalProperty = new Property { IsReadOnly = false, Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = parameter.SerializedName }; parameter.Constraints.ToList().ForEach(x => optionalProperty.Constraints.Add(x.Key, x.Value)); parameter.Extensions.ToList().ForEach(x => optionalProperty.Extensions.Add(x.Key, x.Value)); ((CompositeType)optionsParmeter.Type).Properties.Add(optionalProperty); } //Adding customHeaders to the options object Property customHeaders = new Property { IsReadOnly = false, Name = "customHeaders", IsRequired = false, Documentation = "Headers that will be added to the request", Type = new PrimaryType(KnownPrimaryType.Object), SerializedName = "customHeaders" }; ((CompositeType)optionsParmeter.Type).Properties.Add(customHeaders); OptionsParameterTemplateModel = new ParameterTemplateModel(optionsParmeter); }
public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { if (!string.IsNullOrEmpty(source.PolymorphicDiscriminator)) { if (!source.Properties.Any(p => p.Name == source.PolymorphicDiscriminator)) { var polymorphicProperty = new Property { IsRequired = true, Name = source.PolymorphicDiscriminator, SerializedName = source.PolymorphicDiscriminator, Documentation = "Polymorphic Discriminator", Type = new PrimaryType(KnownPrimaryType.String) { Name = "str" } }; source.Properties.Add(polymorphicProperty); } } this.LoadFrom(source); ServiceClient = serviceClient; if (ServiceClient.ErrorTypes.Contains(source)) { _isException = true; } if (source.BaseModelType != null) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } foreach (var property in ComposedProperties) { if (string.IsNullOrWhiteSpace(property.DefaultValue)) { property.DefaultValue = PythonConstants.None; } } if (this.IsPolymorphic) { foreach (var modelType in ServiceClient.ModelTypes) { if (modelType.BaseModelType == source) { _subModelTypes.Add(modelType); } } } }
public void ParseWithServiceClientWithCreateResourceMethod() { ServiceClient serviceClient = new ServiceClient(); Parameter body = new Parameter() { Location = ParameterLocation.Body, Type = new CompositeType(), }; CompositeType responseBody = new CompositeType(); responseBody.Extensions.Add("x-ms-azure-resource", true); const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}"; Method method = CreateMethod(body: body, responseBody: responseBody, url: url); serviceClient.Methods.Add(method); IDictionary<string, ResourceSchema> schemas = ResourceSchemaParser.Parse(serviceClient); Assert.NotNull(schemas); Assert.Equal(1, schemas.Count); ResourceSchema schema = schemas["Mock.Provider"]; Assert.Null(schema.Id); Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema); Assert.Equal("Mock.Provider", schema.Title); Assert.Equal("Mock Provider Resource Types", schema.Description); Assert.Equal(1, schema.ResourceDefinitions.Count); Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single()); Assert.Equal( new JsonSchema() { JsonType = "object", Description = "Mock.Provider/mockResourceNames" } .AddProperty("type", new JsonSchema() { JsonType = "string" } .AddEnum("Mock.Provider/mockResourceNames"), true), schema.ResourceDefinitions["mockResourceNames"]); Assert.NotNull(schema.Definitions); Assert.Equal(0, schema.Definitions.Count); }
/// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> public virtual void NormalizePaginatedMethods(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var pageTypeFormat = "Page<{0}>"; var convertedTypes = new Dictionary<IType, CompositeType>(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureCodeGenerator.PageableExtension))) { foreach (var responseStatus in method.Responses.Where(r => r.Value is CompositeType).Select(s => s.Key).ToArray()) { var compositType = (CompositeType) method.Responses[responseStatus]; var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if(sequenceType != null && compositType.Properties.Count == 2 && compositType.Properties.Any(p => p.SerializedName.Equals("nextLink", StringComparison.OrdinalIgnoreCase))) { var pagableTypeName = string.Format(CultureInfo.InvariantCulture, pageTypeFormat, sequenceType.ElementType.Name); CompositeType pagedResult = new CompositeType { Name = pagableTypeName }; pagedResult.Extensions[AzureCodeGenerator.ExternalExtension] = true; convertedTypes[method.Responses[responseStatus]] = pagedResult; method.Responses[responseStatus] = pagedResult; } } if (convertedTypes.ContainsKey(method.ReturnType)) { method.ReturnType = convertedTypes[method.ReturnType]; } } AzureCodeGenerator.RemoveUnreferencedTypes(serviceClient, convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name)); }
public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { if (!string.IsNullOrEmpty(source.PolymorphicDiscriminator)) { if (!source.Properties.Any(p => p.Name == source.PolymorphicDiscriminator)) { var polymorphicProperty = new Property { IsRequired = true, Name = source.PolymorphicDiscriminator, SerializedName = source.PolymorphicDiscriminator, Documentation = "Polymorhpic Discriminator", Type = PrimaryType.String }; source.Properties.Add(polymorphicProperty); } } this.LoadFrom(source); ServiceClient = serviceClient; if (source.BaseModelType != null) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } }
/// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> private void NormalizePaginatedMethods(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var convertedTypes = new Dictionary<IType, Response>(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key)) { var compositType = (CompositeType)method.Responses[responseStatus].Body; var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if (sequenceType != null) { string pagableTypeName = GetPagingSetting(method.Extensions, sequenceType.ElementType.Name); CompositeType pagedResult = new CompositeType { Name = pagableTypeName }; convertedTypes[compositType] = new Response(pagedResult, null); method.Responses[responseStatus] = convertedTypes[compositType]; break; } } if (convertedTypes.ContainsKey(method.ReturnType.Body)) { method.ReturnType = convertedTypes[method.ReturnType.Body]; } } AzureExtensions.RemoveUnreferencedTypes(serviceClient, convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name)); }
public override IType BuildServiceType(string serviceTypeName) { // Check if already generated if (serviceTypeName != null && Modeler.GeneratedTypes.ContainsKey(serviceTypeName)) { return Modeler.GeneratedTypes[serviceTypeName]; } _schema = Modeler.Resolver.Unwrap(_schema); // If primitive type if ((_schema.Type != null && _schema.Type != DataType.Object) || _schema.AdditionalProperties != null) { return _schema.GetBuilder(Modeler).ParentBuildServiceType(serviceTypeName); } // If the object does not have any properties, treat it as raw json (i.e. object) if (_schema.Properties.IsNullOrEmpty() && string.IsNullOrEmpty(_schema.Extends)) { return PrimaryType.Object; } // Otherwise create new object type var objectType = new CompositeType { Name = serviceTypeName, SerializedName = serviceTypeName, Documentation = _schema.Description }; // Put this in already generated types serializationProperty Modeler.GeneratedTypes[serviceTypeName] = objectType; if (_schema.Properties != null) { // Visit each property and recursively build service types foreach (var property in _schema.Properties) { string name = property.Key; if (name != _schema.Discriminator) { string propertyServiceTypeName; if (property.Value.Reference != null) { propertyServiceTypeName = property.Value.Reference.StripDefinitionPath(); } else { propertyServiceTypeName = serviceTypeName + "_" + property.Key; } var propertyType = property.Value.GetBuilder(Modeler).BuildServiceType(propertyServiceTypeName); var propertyObj = new Property { Name = name, SerializedName = name, Type = propertyType, IsRequired = property.Value.IsRequired }; //propertyObj.Type = objectType; propertyObj.Documentation = property.Value.Description; var enumType = propertyType as EnumType; if (enumType != null) { if (propertyObj.Documentation == null) { propertyObj.Documentation = string.Empty; } else { propertyObj.Documentation = propertyObj.Documentation.TrimEnd('.') + ". "; } propertyObj.Documentation += "Possible values for this property include: " + string.Join(", ", enumType.Values.Select(v => string.Format(CultureInfo.InvariantCulture, "'{0}'", v.Name))) + "."; } propertyObj.IsReadOnly = property.Value.ReadOnly; objectType.Properties.Add(propertyObj); } else { objectType.PolymorphicDiscriminator = name; } } } // Copy over extensions _schema.Extensions.ForEach(e => objectType.Extensions[e.Key] = e.Value); // Put this in the extended type serializationProperty for building method return type in the end if (_schema.Extends != null) { Modeler.ExtendedTypes[serviceTypeName] = _schema.Extends.StripDefinitionPath(); } return objectType; }
public AzureCompositeTypeModel(CompositeType compositeType, string package) : this(package) { this.LoadFrom(compositeType); }
public override IType BuildServiceType(string serviceTypeName) { // Check if already generated if (serviceTypeName != null && Modeler.GeneratedTypes.ContainsKey(serviceTypeName)) { return Modeler.GeneratedTypes[serviceTypeName]; } _schema = Modeler.Resolver.Unwrap(_schema); // If primitive type if ((_schema.Type != null && _schema.Type != DataType.Object) || _schema.AdditionalProperties != null) { return _schema.GetBuilder(Modeler).ParentBuildServiceType(serviceTypeName); } // If object with file format treat as stream if (_schema.Type != null && _schema.Type == DataType.Object && "file".Equals(SwaggerObject.Format, StringComparison.OrdinalIgnoreCase)) { return PrimaryType.Stream; } // If the object does not have any properties, treat it as raw json (i.e. object) if (_schema.Properties.IsNullOrEmpty() && string.IsNullOrEmpty(_schema.Extends)) { return PrimaryType.Object; } // Otherwise create new object type var objectType = new CompositeType { Name = serviceTypeName, SerializedName = serviceTypeName, Documentation = _schema.Description }; // Put this in already generated types serializationProperty Modeler.GeneratedTypes[serviceTypeName] = objectType; if (_schema.Properties != null) { // Visit each property and recursively build service types foreach (var property in _schema.Properties) { string name = property.Key; if (name != _schema.Discriminator) { string propertyServiceTypeName; if (property.Value.Reference != null) { propertyServiceTypeName = property.Value.Reference.StripDefinitionPath(); } else { propertyServiceTypeName = serviceTypeName + "_" + property.Key; } var propertyType = property.Value.GetBuilder(Modeler).BuildServiceType(propertyServiceTypeName); var propertyObj = new Property { Name = name, SerializedName = name, Type = propertyType, IsRequired = property.Value.IsRequired, IsReadOnly = property.Value.ReadOnly, DefaultValue = property.Value.Default }; SetConstraints(propertyObj.Constraints, property.Value); //propertyObj.Type = objectType; propertyObj.Documentation = property.Value.Description; var enumType = propertyType as EnumType; if (enumType != null) { if (propertyObj.Documentation == null) { propertyObj.Documentation = string.Empty; } else { propertyObj.Documentation = propertyObj.Documentation.TrimEnd('.') + ". "; } propertyObj.Documentation += "Possible values for this property include: " + string.Join(", ", enumType.Values.Select(v => string.Format(CultureInfo.InvariantCulture, "'{0}'", v.Name))) + "."; } objectType.Properties.Add(propertyObj); } else { objectType.PolymorphicDiscriminator = name; } } } // Copy over extensions _schema.Extensions.ForEach(e => objectType.Extensions[e.Key] = e.Value); if (_schema.Extends != null) { // Optionally override the discriminator value for polymorphic types. We expect this concept to be // added to Swagger at some point, but until it is, we use an extension. object discriminatorValueExtension; if (objectType.Extensions.TryGetValue(DiscriminatorValueExtension, out discriminatorValueExtension)) { string discriminatorValue = discriminatorValueExtension as string; if (discriminatorValue != null) { objectType.SerializedName = discriminatorValue; } } // Put this in the extended type serializationProperty for building method return type in the end Modeler.ExtendedTypes[serviceTypeName] = _schema.Extends.StripDefinitionPath(); } return objectType; }
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); }
private void VerifyFirstPropertyIsByteArray(CompositeType serviceType) { var referenceKey = serviceType.Name; var responseType = _swaggerModeler.GeneratedTypes[referenceKey]; var property = responseType.Properties.FirstOrDefault(p => p.Type is PrimaryType && ((PrimaryType)p.Type).Type == KnownPrimaryType.ByteArray); if (property == null) { throw new KeyNotFoundException( "Please specify a field with type of System.Byte[] to deserialize the file contents to"); } }
/// <summary> /// Changes paginated method signatures to return Page type. /// </summary> /// <param name="serviceClient"></param> /// <param name="pageClasses"></param> public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDictionary<KeyValuePair<string, string>, string> pageClasses) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } var convertedTypes = new Dictionary<IType, CompositeType>(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { string nextLinkString; string pageClassName = GetPagingSetting(method.Extensions, pageClasses, out nextLinkString); if (string.IsNullOrEmpty(pageClassName)) { continue; } var pageTypeFormat = "{0}<{1}>"; var ipageTypeFormat = "IPage<{0}>"; if (string.IsNullOrWhiteSpace(nextLinkString)) { ipageTypeFormat = "IEnumerable<{0}>"; } foreach (var responseStatus in method.Responses .Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray()) { var compositType = (CompositeType) method.Responses[responseStatus].Body; var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; // if the type is a wrapper over page-able response if(sequenceType != null) { var pagableTypeName = string.Format(CultureInfo.InvariantCulture, pageTypeFormat, pageClassName, sequenceType.ElementType.Name); var ipagableTypeName = string.Format(CultureInfo.InvariantCulture, ipageTypeFormat, sequenceType.ElementType.Name); CompositeType pagedResult = new CompositeType { Name = pagableTypeName }; pagedResult.Extensions[AzureExtensions.ExternalExtension] = true; pagedResult.Extensions[AzureExtensions.PageableExtension] = ipagableTypeName; convertedTypes[method.Responses[responseStatus].Body] = pagedResult; method.Responses[responseStatus] = new Response(pagedResult, method.Responses[responseStatus].Headers); } } if (convertedTypes.ContainsKey(method.ReturnType.Body)) { method.ReturnType = new Response(convertedTypes[method.ReturnType.Body], method.ReturnType.Headers); } } AzureExtensions.RemoveUnreferencedTypes(serviceClient, convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name)); }
/// <summary> /// Initializes a new instance of the AzureModelTemplateModel class. /// </summary> /// <param name="source">The object to create model from.</param> public AzureModelTemplateModel(CompositeType source) : base(source) { }
private IType NormalizeCompositeType(CompositeType compositeType) { compositeType.Name = GetTypeName(compositeType.Name); foreach (var property in compositeType.Properties) { property.Name = GetPropertyName(property.GetClientName()); property.Type = NormalizeTypeReference(property.Type); } return compositeType; }
/// <summary> /// Determines a composite type as an External Resource if it's name equals "Resource" /// and it has an extension named "x-ms-azure-resource" marked as true. /// </summary> /// <param name="compositeType">Type to determine if it is an external resource</param> /// <returns>True if it is an external resource, false otherwise</returns> public static bool IsAzureResource(CompositeType compositeType) { if (compositeType == null) { return false; } if (compositeType.ComposedExtensions.ContainsKey(AzureResourceExtension)) { var external = compositeType.ComposedExtensions[AzureResourceExtension] as bool?; return (external == null || external.Value); } return false; }
/// <summary> /// Checks whether model should be excluded from producing. /// </summary> /// <param name="model">The model.</param> /// <returns>True if should be excluded, false otherwise.</returns> protected virtual bool ExcludeModel(CompositeType model) { return false; }
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; }
/// <summary> /// Determines whether one composite type derives directly or indirectly from another. /// </summary> /// <param name="type">Type to test.</param> /// <param name="possibleAncestorType">Type that may be an ancestor of this type.</param> /// <returns>true if the type is an ancestor, false otherwise.</returns> public static bool DerivesFrom(this CompositeType type, CompositeType possibleAncestorType) { return type.BaseModelType != null && (type.BaseModelType.Equals(possibleAncestorType) || type.BaseModelType.DerivesFrom(possibleAncestorType)); }
public void ExternalResourceTypeIsNullSafe() { 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 resource = new CompositeType(); var resourceProperties = new CompositeType(); serviceClient.ModelTypes.Add(resource); serviceClient.ModelTypes.Add(resourceProperties); resource.Name = "resource"; 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 }); resource.Extensions[AzureExtensions.AzureResourceExtension] = null; resourceProperties.Name = "resourceProperties"; resourceProperties.Properties.Add(new Property { Name = "parent", Type = PrimaryType.Long, IsRequired = true }); var codeGen = new SampleAzureCodeGenerator(new Settings()); codeGen.NormalizeClientModel(serviceClient); Assert.Equal(2, serviceClient.ModelTypes.Count); }
private static void RemoveFlatteningConflicts(CompositeType compositeType) { if (compositeType == null) { throw new ArgumentNullException("compositeType"); } foreach (Property innerProperty in compositeType.Properties) { // Check conflict among peers var conflictingPeers = compositeType.Properties .Where(p => p.Name == innerProperty.Name && p.SerializedName != innerProperty.SerializedName); if (conflictingPeers.Any()) { foreach (var cp in conflictingPeers.Concat(new[] { innerProperty })) { if (cp.Extensions.ContainsKey(FlattenOriginalTypeName)) { cp.Name = cp.Extensions[FlattenOriginalTypeName].ToString() + "_" + cp.Name; } } } if (compositeType.BaseModelType != null) { var conflictingParentProperties = compositeType.BaseModelType.ComposedProperties .Where(p => p.Name == innerProperty.Name && p.SerializedName != innerProperty.SerializedName); if (conflictingParentProperties.Any()) { innerProperty.Name = compositeType.Name + "_" + innerProperty.Name; } } } }
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" }; }
/// <summary> /// Checks whether model should be excluded from producing. /// </summary> /// <param name="model">The model.</param> /// <returns>True if should be excluded, false otherwise.</returns> protected override bool ExcludeModel(CompositeType model) { return (model.Extensions.ContainsKey(AzureExtensions.ExternalExtension) && (bool) model.Extensions[AzureExtensions.ExternalExtension]) || model.Name == "Resource" || model.Name == "SubResource"; }
public PageTemplateModel(CompositeType source, ServiceClient serviceClient, string nextLinkName, string itemName) : base(source, serviceClient) { this.NextLinkName = nextLinkName; this.ItemName = itemName; }
protected void AddHeaderDictionary(IndentedStringBuilder builder, CompositeType headersType) { if (builder == null) { throw new ArgumentNullException("builder"); } if (headersType == null) { throw new ArgumentNullException("headersType"); } foreach (var prop in headersType.Properties) { if (this.ServiceClient.EnumTypes.Contains(prop.Type)) { builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': models.{1},", prop.SerializedName, prop.Type.ToPythonRuntimeTypeString())); } else { builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': '{1}',", prop.SerializedName, prop.Type.ToPythonRuntimeTypeString())); } } }
/// <summary> /// Normalizes composite type. /// </summary> /// <param name="compositeType">Type to normalize.</param> /// <returns>Normalized type.</returns> private IType NormalizeCompositeType(CompositeType compositeType) { compositeType.Name = GetTypeName(compositeType.Name); foreach (var property in compositeType.Properties) { property.Name = GetPropertyName(property.GetClientName()); if (property.SerializedName != null && !property.WasFlattened()) { property.SerializedName = property.SerializedName.Replace(".", "\\\\."); } property.Type = NormalizeTypeReference(property.Type); } return compositeType; }