public AzureCSharpFluentCodeNamer(Settings settings)
            :base(settings)
        {
            _innerTypes = new HashSet<CompositeType>();

            _resourceType = new CompositeType
            {
                Name = "Microsoft.Rest.Azure.Resource",
                SerializedName = "Resource",
            };

            var stringType = new PrimaryType(KnownPrimaryType.String)
            {
                Name = "string"
            };
            _resourceType.Properties.Add(new Property { Name = "location", SerializedName = "location", Type = stringType });
            _resourceType.Properties.Add(new Property { Name = "id", SerializedName = "id", Type = stringType });
            _resourceType.Properties.Add(new Property { Name = "name", SerializedName = "name", Type = stringType });
            _resourceType.Properties.Add(new Property { Name = "type", SerializedName = "type", Type = stringType });
            _resourceType.Properties.Add(new Property { Name = "tags", SerializedName = "tags", Type = new DictionaryType { ValueType = stringType, NameFormat = "System.Collections.Generic.IDictionary<string, {0}>" } });

            _subResourceType = new CompositeType
            {
                Name = "Microsoft.Rest.Azure.SubResource",
                SerializedName = "SubResource"
            };
            _subResourceType.Properties.Add(new Property { Name = "id", SerializedName = "id", Type = stringType });
        }
        public void NameCollisionTestWithoutNamespace()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";

            var customObjectType = new CompositeType();
            customObjectType.Name = "azure always rocks!";

            var baseType = new CompositeType();
            baseType.Name = "azure always rocks!";

            serviceClient.Methods.Add(new Method
            {
                Name = "azure always rocks!",
                Group = "azure always rocks!",
                ReturnType = new Response(customObjectType, null)
            });

            serviceClient.ModelTypes.Add(customObjectType);
            serviceClient.ModelTypes.Add(baseType);

            var framework = new CSharpCodeNamer();
            framework.ResolveNameCollisions(serviceClient, null, null);

            Assert.Equal("azure always rocks!Client", serviceClient.Name);
            Assert.Equal("azure always rocks!Operations", serviceClient.MethodGroups.First());
            Assert.Equal("azure always rocks!", serviceClient.Methods[0].Name);
            Assert.Equal("azure always rocks!", serviceClient.ModelTypes.First(m => m.Name == "azure always rocks!").Name);
        }
        public ModelTemplateModel(CompositeType source)
        {
            this.LoadFrom(source);

            PropertyTemplateModels = new List<PropertyTemplateModel>();
            source.Properties.ForEach(p => PropertyTemplateModels.Add(new PropertyTemplateModel(p)));
        }
 public AzureFluentModelTemplateModel(CompositeType source, ServiceClient serviceClient)
     : base(source, serviceClient)
 {
     _namer = new AzureJavaFluentCodeNamer(serviceClient.Namespace);
     PropertyModels = new List<PropertyModel>();
     Properties.ForEach(p => PropertyModels.Add(new FluentPropertyModel(p, serviceClient.Namespace, IsInnerModel)));
 }
        /// <summary>
        /// Initializes a new instance of the ModelTemplateModel class.
        /// </summary>
        /// <param name="source">The object to create model from.</param>
        /// <param name="allTypes">The list of all model types; Used to implement polymorphism.</param>
        public ModelTemplateModel(CompositeType source, ISet<CompositeType> allTypes)
        {
            this.LoadFrom(source);
            PropertyTemplateModels = new List<PropertyTemplateModel>();
            source.Properties.ForEach(p => PropertyTemplateModels.Add(new PropertyTemplateModel(p)));

            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 = new PrimaryType(KnownPrimaryType.String)
                    };
                    source.Properties.Add(polymorphicProperty);
                }
            }

            if (source.BaseModelType != null)
            {
                this.parent = new ModelTemplateModel(source.BaseModelType, allTypes);
            }

            this.allTypes = allTypes;
        }
 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);
            }

            this._constructorModel = new ConstructorModel(this);
        }
 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)));
 }
        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);
        }
 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 = new PrimaryType(KnownPrimaryType.String)
             };
             source.Properties.Add(polymorphicProperty);
         }
     }
     this.LoadFrom(source);
     ServiceClient = serviceClient;
     if (source.BaseModelType != null)
     {
         _parent = new ModelTemplateModel(source.BaseModelType, serviceClient);
     }
 }
        public void VerifyInputMappingsForFlattening()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "test service client";

            var customObjectType = new CompositeType();
            customObjectType.Name = "Foo";
            customObjectType.Properties.Add(new Property
            {
                Name = "A",
                Type = new PrimaryType(KnownPrimaryType.Boolean)
            });
            customObjectType.Properties.Add(new Property
            {
                Name = "B",
                Type = new PrimaryType(KnownPrimaryType.String)
            });
            var method = new Method
            {
                Name = "method1",
                Group = "mGroup",
                ReturnType = new Response(customObjectType, null)
            };
            var outputParameter = new Parameter { Name = "body", Type = customObjectType };
            serviceClient.Methods.Add(method);
            method.Parameters.Add(new Parameter { Name = "paramA", Type = new PrimaryType(KnownPrimaryType.Boolean), SerializedName = "paramA" });
            method.Parameters.Add(new Parameter { Name = "paramB", Type = new PrimaryType(KnownPrimaryType.String), SerializedName = "paramB" });
            method.InputParameterTransformation.Add(new ParameterTransformation
            {
                OutputParameter = outputParameter
            });
            method.InputParameterTransformation[0].ParameterMappings.Add(new ParameterMapping
            {
                InputParameter = method.Parameters[0],
                OutputParameterProperty = "A"
            });
            method.InputParameterTransformation[0].ParameterMappings.Add(new ParameterMapping
            {
                InputParameter = method.Parameters[1],
                OutputParameterProperty = "B"
            });

            MethodTemplateModel templateModel = new MethodTemplateModel(method, serviceClient,SyncMethodsGenerationMode.All);
            var output = templateModel.BuildInputMappings();
            System.Console.WriteLine(output);
            string expected =
              @"Foo body = default(Foo);
            if (paramA != null || paramB != null)
            {
                body = new Foo();
                body.A = paramA;
                body.B = paramB;
            }";

            MultilineAreEqual(expected, output.Trim());
        }
 public FluentCompositeTypeModel(CompositeType compositeType, string package)
     : base(compositeType, package)
 {
     this.LoadFrom(compositeType);
 }
 public static IndentedStringBuilder ConstructPolymorphicDiscriminator(CompositeType composite, IndentedStringBuilder builder)
 {
     if (composite == null)
     {
         throw new ArgumentNullException("composite");
     }
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     // Note: If the polymorphicDiscriminator has a dot in it's name then do not escape that dot for
     // it's serializedName, the way it is done for other properties. This makes it easy to find the
     // discriminator property from the responseBody during deserialization. Please, do not get confused
     // between the definition of the discriminator and the definition of the property that is
     // marked as the discriminator.
     builder.AppendLine("polymorphicDiscriminator: {")
              .Indent()
              .AppendLine("serializedName: '{0}',", composite.PolymorphicDiscriminator)
              .AppendLine("clientName: '{0}'", new NodeJsCodeNamer().GetPropertyName(composite.PolymorphicDiscriminator))
            .Outdent()
            .AppendLine("},");
     var polymorphicType = composite;
     while (polymorphicType.BaseModelType != null)
     {
         polymorphicType = polymorphicType.BaseModelType;
     }
     builder.AppendLine("uberParent: '{0}',", polymorphicType.Name);
     return builder;
 }
        private string GetPagingSetting(CompositeType body, Dictionary<string, object> extensions, string valueTypeName, IDictionary<int, string> typePageClasses, String methodName)
        {
            var ext = extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer;

            bool ignoreNextLink = false;
            if (ext["nextLinkName"] != null && ext["nextLinkName"].Type == Newtonsoft.Json.Linq.JTokenType.Null)
            {
                ignoreNextLink = true;
            }
            string nextLinkName = (string)ext["nextLinkName"] ?? "nextLink";
            string itemName = (string)ext["itemName"] ?? "value";

            nextLinkName = nextLinkName.Replace(".", "\\\\.");
            itemName = itemName.Replace(".", "\\\\.");
            bool findNextLink = false;
            bool findItem = false;
            foreach (var property in body.ComposedProperties)
            {
                if (property.SerializedName == nextLinkName)
                {
                    findNextLink = true;
                }
                else if (property.SerializedName == itemName)
                {
                    findItem = true;
                }
            }

            if (!ignoreNextLink && !findNextLink)
            {
                throw new KeyNotFoundException(String.Format(CultureInfo.InvariantCulture, "Couldn't find the nextLink property specified by extension on operation {0} and property {1}", methodName, body.SerializedName));
            }
            if (!findItem)
            {
                throw new KeyNotFoundException("Couldn't find the item property specified by extension");
            }

            string className;
            var hash = (nextLinkName + "#" + itemName).GetHashCode();
            if (!typePageClasses.ContainsKey(hash))
            {
                className = (string)ext["className"];
                if (string.IsNullOrEmpty(className))
                {
                    if (typePageClasses.Count > 0)
                    {
                        className = valueTypeName + String.Format(CultureInfo.InvariantCulture, "Paged{0}", typePageClasses.Count);
                    }
                    else
                    {
                        className = valueTypeName + "Paged";
                    }
                }
                typePageClasses.Add(hash, className);
            }

            className = typePageClasses[hash];
            ext["className"] = className;

            var pageModel = new PageTemplateModel(className, nextLinkName, itemName, valueTypeName);
            if (!pageModels.Contains(pageModel))
            {
                pageModels.Add(pageModel);
            }

            return className;
        }
 public AzureModelTemplateModel(CompositeType source, ServiceClient serviceClient)
     : base(source, serviceClient)
 {
     _namer = new AzureJavaCodeNamer(serviceClient.Namespace);
 }
Example #16
0
 public CompositeTypeModel(CompositeType compositeType, string package)
     : this(package)
 {
     this.LoadFrom(compositeType);
 }
        /// <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 valueType = sequenceType.ElementType.Name;
                        if (!pageClasses.ContainsKey(valueType))
                        {
                            pageClasses.Add(valueType, new Dictionary<int, string>());
                        }
                        string pagableTypeName = GetPagingSetting(compositType, method.Extensions, valueType, pageClasses[valueType], method.SerializedName);

                        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];
                }
            }

            SwaggerExtensions.RemoveUnreferencedTypes(serviceClient, new HashSet<string>(convertedTypes.Keys.Cast<CompositeType>().Select(t => t.Name)));
        }
        public void SequenceWithRenamedComplexType()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";

            var complexType = new CompositeType();
            complexType.Name = "Greetings";

            serviceClient.Methods.Add(new Method
            {
                Name = "List",
                ReturnType = new Response(new SequenceType { ElementType = complexType }, null)
            });

            serviceClient.Methods.Add(new Method
            {
                Name = "List2",
                ReturnType = new Response(new DictionaryType { ValueType = complexType }, null)
            });

            serviceClient.ModelTypes.Add(complexType);

            var codeGenerator = new CSharpCodeGenerator(new Settings { Namespace = "Polar.Greetings" });
            codeGenerator.NormalizeClientModel(serviceClient);

            Assert.Equal("GreetingsModel", complexType.Name);
            Assert.Equal("System.Collections.Generic.IList<GreetingsModel>", serviceClient.Methods[0].ReturnType.Body.Name);
            Assert.Equal("System.Collections.Generic.IDictionary<string, GreetingsModel>", serviceClient.Methods[1].ReturnType.Body.Name);
        }
Example #19
0
 public PageTemplateModel(CompositeType source, ServiceClient serviceClient, string nextLinkName, string itemName) 
     : base(source, serviceClient)
 {
     this.NextLinkName = nextLinkName;
     this.ItemName = itemName;
 }
Example #20
0
        protected virtual 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);
                if (!property.IsRequired)
                {
                    property.Type = WrapPrimitiveType(property.Type);
                }
            }

            if (compositeType.BaseModelType != null) {
                compositeType.BaseModelType = (CompositeType) NormalizeTypeReference(compositeType.BaseModelType);
            }

            return compositeType;
        }
Example #21
0
 protected virtual CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType)
 {
     return new CompositeTypeModel(compositeType, _package);
 }
        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);
        }
Example #23
0
        /// <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;
        }
        public void TypeNormalizationWithComplexTypesTest()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";

            var childObject = new CompositeType();
            childObject.Name = "child";
            childObject.Properties.Add(new Property
            {
                Name = "childProperty",
                Type = new PrimaryType(KnownPrimaryType.String)
            });

            var customObjectType = new CompositeType();
            customObjectType.Name = "sample";
            customObjectType.Properties.Add(new Property
            {
                Name = "child",
                Type = childObject
            });
            customObjectType.Properties.Add(new Property
            {
                Name = "childList",
                Type = new SequenceType
                {
                    ElementType = childObject
                }
            });
            customObjectType.Properties.Add(new Property
            {
                Name = "childDict",
                Type = new DictionaryType
                {
                    ValueType = childObject
                }
            });

            serviceClient.ModelTypes.Add(customObjectType);
            serviceClient.ModelTypes.Add(childObject);

            var framework = new CSharpCodeNamer();
            framework.NormalizeClientModel(serviceClient);
            framework.ResolveNameCollisions(serviceClient, "SampleNs", "SampleNs.Models");

            Assert.Equal("Sample", serviceClient.ModelTypes.First(m => m.Name == "Sample").Name);
            Assert.Equal("Child", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[0].Name);
            Assert.Equal("Child", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[0].Type.Name);
            Assert.Equal("ChildList", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[1].Name);
            Assert.Equal("System.Collections.Generic.IList<Child>", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[1].Type.Name);
            Assert.Equal("ChildDict", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[2].Name);
            Assert.Equal("System.Collections.Generic.IDictionary<string, Child>", serviceClient.ModelTypes.First(m => m.Name == "Sample").Properties[2].Type.Name);
            Assert.Equal("Child", serviceClient.ModelTypes.First(m => m.Name == "Child").Name);
            Assert.Equal("string", serviceClient.ModelTypes.First(m => m.Name == "Child").Properties[0].Type.Name);
        }
        public void TypeNormalizationTest()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";
            serviceClient.Properties.Add(new Property
            {
                Name = "&%$ i rock too!",
                Type = new PrimaryType(KnownPrimaryType.Int)
            });
            serviceClient.Properties.Add(new Property
            {
                Name = "some-other-stream",
                Type = new PrimaryType(KnownPrimaryType.Stream)
            });

            var customObjectType = new CompositeType();
            customObjectType.Name = "!@#$%^&*()abc";
            customObjectType.SerializedName = "!@#$%^&*()abc";
            customObjectType.Properties.Add(new Property
            {
                Name = "boolean-property",
                Type = new PrimaryType(KnownPrimaryType.Boolean)
            });
            customObjectType.Properties.Add(new Property
            {
                Name = "some^dateTime_sequence",
                Type = new SequenceType
                {
                    ElementType = new PrimaryType(KnownPrimaryType.DateTime)
                }
            });

            var baseType = new CompositeType();
            baseType.Name = "baseType";
            baseType.SerializedName = "baseType";
            baseType.Properties.Add(new Property
            {
                Name = "boolean-property",
                SerializedName = "boolean-property",
                Type = new PrimaryType(KnownPrimaryType.Boolean)
            });
            baseType.BaseModelType = baseType;
            baseType.Properties.Add(new Property
            {
                Name = "self-property",
                SerializedName = "self-property",
                Type = baseType
            });

            customObjectType.BaseModelType = baseType;

            serviceClient.ModelTypes.Add(customObjectType);
            serviceClient.ModelTypes.Add(baseType);

            var framework = new CSharpCodeNamer();
            framework.NormalizeClientModel(serviceClient);

            Assert.Equal("Azurealwaysrocks", serviceClient.Name);
            Assert.Equal("Abc", serviceClient.ModelTypes.First(m => m.Name == "Abc").Name);
            Assert.Equal("!@#$%^&*()abc", serviceClient.ModelTypes.First(m => m.Name == "Abc").SerializedName);
            Assert.Equal("BooleanProperty", serviceClient.ModelTypes.First(m => m.Name == "Abc").Properties[0].Name);
            Assert.Equal("SomedateTimeSequence", serviceClient.ModelTypes.First(m => m.Name == "Abc").Properties[1].Name);
            Assert.Equal("BaseType", serviceClient.ModelTypes.First(m => m.Name == "BaseType").Name);
            Assert.Equal("baseType", serviceClient.ModelTypes.First(m => m.Name == "BaseType").SerializedName);
            Assert.Equal("BooleanProperty", serviceClient.ModelTypes.First(m => m.Name == "BaseType").Properties[0].Name);
            Assert.Equal("boolean-property", serviceClient.ModelTypes.First(m => m.Name == "BaseType").Properties[0].SerializedName);
            Assert.Equal("SelfProperty", serviceClient.ModelTypes.First(m => m.Name == "BaseType").Properties[1].Name);
            Assert.Equal("self-property", serviceClient.ModelTypes.First(m => m.Name == "BaseType").Properties[1].SerializedName);
        }
Example #26
0
        private IType NormalizeCompositeType(CompositeType compositeType)
        {
            // Composite types normalize to the same object
            _normalizedTypes[compositeType] = compositeType;

            compositeType.Name = GetTypeName(compositeType.Name);

            foreach (var property in compositeType.Properties)
            {
                property.SerializedName = property.Name;
                property.Name = GetPropertyName(property.Name);
                // gosdk: For now, inherit Enumerated type names from the composite type field name
                if (property.Type is EnumType)
                {
                    var enumType = property.Type as EnumType;
                    if (String.IsNullOrEmpty(enumType.Name))
                    {
                        enumType.Name = property.Name;
                    }
                }
                property.Type = NormalizeTypeReference(property.Type);
            }

            return compositeType;
        }
Example #27
0
 protected override CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType)
 {
     return new AzureCompositeTypeModel(compositeType, _package);
 }
        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());
        }
        private static JsonSchema ParseCompositeType(Property property, CompositeType compositeType, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            string definitionName = compositeType.Name;

            if (!definitions.ContainsKey(definitionName))
            {
                JsonSchema definition = new JsonSchema()
                {
                    JsonType = "object",
                    Description = compositeType.Documentation
                };

                // This definition must be added to the definition map before we start parsing
                // its properties because its properties may recursively reference back to this
                // definition.
                definitions.Add(definitionName, definition);

                foreach (Property subProperty in compositeType.ComposedProperties)
                {
                    JsonSchema subPropertyDefinition = ParseType(subProperty, subProperty.Type, definitions, modelTypes);
                    if (subPropertyDefinition != null)
                    {
                        definition.AddProperty(subProperty.Name, subPropertyDefinition, subProperty.IsRequired);
                    }
                }

                string discriminatorPropertyName = compositeType.PolymorphicDiscriminator;
                if (!string.IsNullOrWhiteSpace(discriminatorPropertyName))
                {
                    CompositeType[] subTypes = modelTypes.Where(modelType => modelType.BaseModelType == compositeType).ToArray();
                    if (subTypes != null && subTypes.Length > 0)
                    {
                        JsonSchema discriminatorDefinition = new JsonSchema()
                        {
                            JsonType = "string"
                        };

                        if (subTypes.Length == 1)
                        {
                            CompositeType subType = subTypes[0];
                            if (subType != null)
                            {
                                foreach (Property subTypeProperty in subType.Properties)
                                {
                                    JsonSchema subTypePropertyDefinition = ParseType(subTypeProperty, subTypeProperty.Type, definitions, modelTypes);
                                    if (subTypePropertyDefinition != null)
                                    {
                                        definition.AddProperty(subTypeProperty.Name, subTypePropertyDefinition, subTypeProperty.IsRequired);
                                    }
                                }

                                const string discriminatorValueExtensionName = "x-ms-discriminator-value";
                                if (subType.ComposedExtensions.ContainsKey(discriminatorValueExtensionName))
                                {
                                    string discriminatorValue = subType.ComposedExtensions[discriminatorValueExtensionName] as string;
                                    if (!string.IsNullOrWhiteSpace(discriminatorValue))
                                    {
                                        discriminatorDefinition.AddEnum(discriminatorValue);
                                    }
                                }
                            }

                            definition.AddProperty(discriminatorPropertyName, discriminatorDefinition);
                        }
                        else
                        {
                            string errorMessage = string.Format(
                                CultureInfo.CurrentCulture,
                                "Multiple sub-types ({0}) of a polymorphic discriminated type ({1}) are not currently supported.",
                                string.Join(", ", subTypes.Select(subType => subType.Name)),
                                compositeType.Name);
                            throw new NotSupportedException(errorMessage);
                        }
                    }
                }
            }

            JsonSchema result = new JsonSchema()
            {
                Ref = "#/definitions/" + definitionName
            };

            if (property != null)
            {
                result.Description = RemovePossibleValuesFromDescription(property.Documentation);
            }

            return result;
        }
        public void VerifyMethodRenaming()
        {
            var serviceClient = new ServiceClient();
            serviceClient.Name = "azure always rocks!";

            var customObjectType = new CompositeType();
            customObjectType.Name = "!@#$%^&*()abc";
            customObjectType.Properties.Add(new Property
            {
                Name = "boolean-property",
                Type = new PrimaryType(KnownPrimaryType.Boolean)
            });
            serviceClient.Methods.Add(new Method
            {
                Name = " method name with lots of spaces",
                Group = "#$% group with lots of-weird-characters",
                ReturnType = new Response(customObjectType, null)
            });

            var framework = new CSharpCodeNamer();
            framework.NormalizeClientModel(serviceClient);

            Assert.Equal("Methodnamewithlotsofspaces", serviceClient.Methods[0].Name);
            Assert.Equal("GroupwithlotsofWeirdCharacters", serviceClient.Methods[0].Group);
            Assert.Equal("Abc", serviceClient.Methods[0].ReturnType.Body.Name);
        }