コード例 #1
0
ファイル: AutoRest.cs プロジェクト: BretJohnson/autorest
 /// <summary>
 /// Generates client using provided settings.
 /// </summary>
 /// <param name="settings">Code generator settings.</param>
 public static void Generate(Settings settings)
 {
     if (settings == null)
     {
         throw new ArgumentNullException("settings");
     }
     Logger.Entries.Clear();
     Logger.LogInfo(Resources.AutoRestCore, Version);
     settings.Validate();
     CodeGenerator codeGenerator = ExtensionsLoader.GetCodeGenerator(settings);
     Modeler modeler = ExtensionsLoader.GetModeler(settings);
     ServiceClient serviceClient;
     try
     {
         serviceClient = modeler.Build();
     }
     catch (Exception exception)
     {
         throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message);
     }
     try
     {
         codeGenerator.NormalizeClientModel(serviceClient);
         codeGenerator.Generate(serviceClient).GetAwaiter().GetResult();
     }
     catch (Exception exception)
     {
         throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message);
     }
 }
コード例 #2
0
ファイル: Extensions.cs プロジェクト: xingwu1/autorest
 /// <summary>
 /// Normalizes client model using generic extensions.
 /// </summary>
 /// <param name="serviceClient">Service client</param>
 /// <param name="settings">AutoRest settings</param>
 /// <returns></returns>
 public static void NormalizeClientModel(ServiceClient serviceClient, Settings settings)
 {
     FlattenModels(serviceClient);
     FlattenMethodParameters(serviceClient, settings);
     ParameterGroupExtensionHelper.AddParameterGroups(serviceClient);
     ProcessParameterizedHost(serviceClient, settings);
 }
コード例 #3
0
ファイル: Extensions.cs プロジェクト: jkonecki/autorest
        public static void ProcessParameterizedHost(ServiceClient serviceClient, Settings settings)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (serviceClient.Extensions.ContainsKey(ParameterizedHostExtension) && !hostChecked)
            { 
                SwaggerModeler modeler = new SwaggerModeler(settings);
                modeler.Build();
                var hostExtension = serviceClient.Extensions[ParameterizedHostExtension] as JObject;

                if (hostExtension != null)
                {
                    var hostTemplate = (string)hostExtension["hostTemplate"];
                    var parametersJson = hostExtension["parameters"].ToString();
                    if (!string.IsNullOrEmpty(parametersJson))
                    {
                        var jsonSettings = new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.None,
                            MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                        };

                        var swaggerParams = JsonConvert.DeserializeObject<List<SwaggerParameter>>(parametersJson, jsonSettings);
                        
                        foreach (var swaggerParameter in swaggerParams)
                        {
                            // Build parameter
                            var parameterBuilder = new ParameterBuilder(swaggerParameter, modeler);
                            var parameter = parameterBuilder.Build();

                            // check to see if the parameter exists in properties, and needs to have its name normalized
                            if (serviceClient.Properties.Any(p => p.SerializedName.Equals(parameter.SerializedName)))
                            {
                                parameter.ClientProperty = serviceClient.Properties.Single(p => p.SerializedName.Equals(parameter.SerializedName));
                            }
                            parameter.Extensions["hostParameter"] = true;

                            foreach (var method in serviceClient.Methods)
                            {
                                method.Parameters.Add(parameter);
                            }
                        }

                        serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}",
                        modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(),
                        hostTemplate, modeler.ServiceDefinition.BasePath);
                    }
                }
            }

            hostChecked = true;
        }
コード例 #4
0
ファイル: SwaggerModeler.cs プロジェクト: maxkeller/autorest
        public SwaggerModeler(Settings settings) : base(settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            DefaultProtocol = TransferProtocolScheme.Http;
        }
コード例 #5
0
ファイル: Modeler.cs プロジェクト: Ranjana1996/autorest
 protected Modeler(Settings settings)
 {
     Settings = settings;
 }
コード例 #6
0
 public SampleAzureCodeGenerator(Settings settings) : base(settings)
 {
 }
コード例 #7
0
ファイル: Settings.cs プロジェクト: xingwu1/autorest
        /// <summary>
        /// Factory method to generate Settings from a dictionary. Matches dictionary
        /// keys to the settings properties.
        /// </summary>
        /// <param name="settings">Dictionary of settings</param>
        /// <returns>Settings</returns>
        public static Settings Create(IDictionary<string, object> settings)
        {
            var autoRestSettings = new Settings();
            if (settings == null || settings.Count == 0)
            {
                autoRestSettings.ShowHelp = true;
            }

            PopulateSettings(autoRestSettings, settings);

            autoRestSettings.CustomSettings = settings;
            if (!string.IsNullOrEmpty(autoRestSettings.CodeGenSettings))
            {
                var settingsContent = autoRestSettings.FileSystem.ReadFileAsText(autoRestSettings.CodeGenSettings);
                var codeGenSettingsDictionary =
                    JsonConvert.DeserializeObject<Dictionary<string, object>>(settingsContent);
                foreach (var pair in codeGenSettingsDictionary)
                {
                    autoRestSettings.CustomSettings[pair.Key] = pair.Value;
                }
            }
            return autoRestSettings;
        }
コード例 #8
0
ファイル: Extensions.cs プロジェクト: xingwu1/autorest
        public static void ProcessParameterizedHost(ServiceClient serviceClient, Settings settings)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (serviceClient.Extensions.ContainsKey(ParameterizedHostExtension) && !hostChecked)
            { 
                SwaggerModeler modeler = new SwaggerModeler(settings);
                modeler.Build();
                var hostExtension = serviceClient.Extensions[ParameterizedHostExtension] as JObject;

                if (hostExtension != null)
                {
                    var hostTemplate = (string)hostExtension["hostTemplate"];
                    var parametersJson = hostExtension["parameters"].ToString();
                    var useSchemePrefix = true;
                    if (hostExtension[UseSchemePrefix] != null)
                    {
                        useSchemePrefix = bool.Parse(hostExtension[UseSchemePrefix].ToString());
                    }

                    var position = "first";
                    
                    if (hostExtension[PositionInOperation] != null)
                    {
                        var pat = "^(fir|la)st$";
                        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
                        var text = hostExtension[PositionInOperation].ToString();
                        Match m = r.Match(text);
                        if (!m.Success)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, 
                                Resources.InvalidExtensionProperty, text, PositionInOperation, ParameterizedHostExtension, "first, last"));
                        }
                        position = text;
                    }

                    if (!string.IsNullOrEmpty(parametersJson))
                    {
                        var jsonSettings = new JsonSerializerSettings
                        {
                            TypeNameHandling = TypeNameHandling.None,
                            MetadataPropertyHandling = MetadataPropertyHandling.Ignore
                        };

                        var swaggerParams = JsonConvert.DeserializeObject<List<SwaggerParameter>>(parametersJson, jsonSettings);
                        List<Parameter> hostParamList = new List<Parameter>();
                        foreach (var swaggerParameter in swaggerParams)
                        {
                            // Build parameter
                            var parameterBuilder = new ParameterBuilder(swaggerParameter, modeler);
                            var parameter = parameterBuilder.Build();

                            // check to see if the parameter exists in properties, and needs to have its name normalized
                            if (serviceClient.Properties.Any(p => p.SerializedName.Equals(parameter.SerializedName)))
                            {
                                parameter.ClientProperty = serviceClient.Properties.Single(p => p.SerializedName.Equals(parameter.SerializedName));
                            }
                            parameter.Extensions["hostParameter"] = true;
                            hostParamList.Add(parameter);
                        }

                        foreach (var method in serviceClient.Methods)
                        {
                            if (position.Equals("first", StringComparison.OrdinalIgnoreCase))
                            {
                                method.Parameters.InsertRange(0, hostParamList);
                            }
                            else
                            {
                                method.Parameters.AddRange(hostParamList);
                            }
                            
                        }
                        if (useSchemePrefix)
                        {
                            serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}",
                                modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(),
                                hostTemplate, modeler.ServiceDefinition.BasePath);
                        }
                        else
                        {
                            serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}",
                                hostTemplate, modeler.ServiceDefinition.BasePath);
                        }
                        
                    }
                }
            }

            hostChecked = true;
        }
コード例 #9
0
ファイル: Extensions.cs プロジェクト: xingwu1/autorest
        /// <summary>
        /// Flattens the request payload if the number of properties of the 
        /// payload is less than or equal to the PayloadFlatteningThreshold.
        /// </summary>
        /// <param name="serviceClient">Service client</param>                            
        /// <param name="settings">AutoRest settings</param>                            
        public static void FlattenMethodParameters(ServiceClient serviceClient, Settings settings)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");    
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            foreach (var method in serviceClient.Methods)
            {
                var bodyParameter = method.Parameters.FirstOrDefault(
                    p => p.Location == ClientModel.ParameterLocation.Body);

                if (bodyParameter != null)
                {
                    var bodyParameterType = bodyParameter.Type as CompositeType;
                    if (bodyParameterType != null && 
                        (bodyParameterType.ComposedProperties.Count(p => !p.IsConstant) <= settings.PayloadFlatteningThreshold ||
                         bodyParameter.ShouldBeFlattened()))
                    {
                        var parameterTransformation = new ParameterTransformation
                        {
                            OutputParameter = bodyParameter
                        };
                        method.InputParameterTransformation.Add(parameterTransformation);

                        foreach (var property in bodyParameterType.ComposedProperties.Where(p => !p.IsConstant && p.Name != null))
                        {
                            var newMethodParameter = new Parameter();
                            newMethodParameter.LoadFrom(property);
                            bodyParameter.Extensions.ForEach(kv => { newMethodParameter.Extensions[kv.Key] = kv.Value; });
                            method.Parameters.Add(newMethodParameter);

                            parameterTransformation.ParameterMappings.Add(new ParameterMapping
                            {
                                InputParameter = newMethodParameter,
                                OutputParameterProperty = property.GetClientName()
                            });
                        }

                        method.Parameters.Remove(bodyParameter);
                    }
                }
            }
        }
コード例 #10
0
        public void TestParameterizedHostFromSwagger()
        {
            var settings = new Settings
            {
                Namespace = "Test",
                Modeler = "Swagger",
                CodeGenerator = "CSharp",
                Input = Path.Combine("Swagger", "swagger-x-ms-parameterized-host.json"),
                Header = "NONE"
            };

            var modeler = ExtensionsLoader.GetModeler(settings);
            var client = modeler.Build();

            var hostExtension = client.Extensions["x-ms-parameterized-host"] as JObject;
            Assert.NotNull(hostExtension);
            
            var hostTemplate = (string)hostExtension["hostTemplate"];
            var jArrayParameters = hostExtension["parameters"] as JArray;
            Assert.NotNull(jArrayParameters);

            Assert.Equal(2, jArrayParameters.Count);
            Assert.Equal("{accountName}.{host}", hostTemplate);
        }
コード例 #11
0
        public void TestSettingsFromSwagger()
        {
            var settings = new Settings
            {
                Namespace = "Test",
                Modeler = "Swagger",
                CodeGenerator = "CSharp",
                Input = Path.Combine("Swagger", "swagger-x-ms-code-generation-settings.json"),
                Header = "NONE"
            };
            var modeler = ExtensionsLoader.GetModeler(settings);
            var client = modeler.Build();
            var codeGenerator = ExtensionsLoader.GetCodeGenerator(settings) as CSharpCodeGenerator;
            settings.Validate();

            Assert.Equal("MIT", settings.Header);
            Assert.Equal(true, codeGenerator.InternalConstructors);
        }
コード例 #12
0
ファイル: Settings.cs プロジェクト: maxkeller/autorest
        /// <summary>
        /// Factory method to generate Settings from a dictionary. Matches dictionary 
        /// keys to the settings properties.
        /// </summary>
        /// <param name="settings">Dictionary of settings</param>
        /// <returns>Settings</returns>
        public static Settings Create(IDictionary<string, string> settings)
        {
            var autoRestSettings = new Settings();
            var unmatchedSettings = PopulateSettings(autoRestSettings, settings);
            if (settings == null || settings.Count > 0)
            {
                autoRestSettings.ShowHelp = true;
            }

            autoRestSettings.CustomSettings = unmatchedSettings;
            return autoRestSettings;
        }
コード例 #13
0
        /// <summary>
        /// Factory method to generate Settings from a dictionary. Matches dictionary 
        /// keys to the settings properties.
        /// </summary>
        /// <param name="settings">Dictionary of settings</param>
        /// <returns>Settings</returns>
        public static Settings Create(IDictionary<string, string> settings)
        {
            var autoRestSettings = new Settings();
            if (settings != null && settings.Count > 0)
            {
                // Setting property value from dictionary
                foreach (var setting in settings)
                {
                    PropertyInfo property = (typeof (Settings)).GetProperties()
                        .FirstOrDefault(p => p.Name.Equals(setting.Key, StringComparison.OrdinalIgnoreCase));

                    if (property != null)
                    {
                        try
                        {
                            if (setting.Value.IsNullOrEmpty() && property.PropertyType == typeof (bool))
                            {
                                property.SetValue(autoRestSettings, true);
                            }
                            else
                            {
                                property.SetValue(autoRestSettings,
                                    Convert.ChangeType(setting.Value, property.PropertyType, CultureInfo.InvariantCulture), null);
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.ParameterValueIsNotValid,
                                setting.Key, property.GetType().Name), exception);
                        }
                    }
                    else
                    {
                        autoRestSettings.CustomSettings[setting.Key] = setting.Value;
                    }
                }
            }
            else
            {
                autoRestSettings.CustomSettings["?"] = String.Empty;
            }

            return autoRestSettings;
        }
コード例 #14
0
ファイル: Extensions.cs プロジェクト: JamesTryand/autorest
 /// <summary>
 /// Normalizes client model using generic extensions.
 /// </summary>
 /// <param name="serviceClient">Service client</param>
 /// <param name="settings">AutoRest settings</param>
 /// <returns></returns>
 public static void NormalizeClientModel(ServiceClient serviceClient, Settings settings)
 {
     FlattenRequestPayload(serviceClient, settings);
     AddParameterGroups(serviceClient);
 }
コード例 #15
0
ファイル: Extensions.cs プロジェクト: JamesTryand/autorest
        /// <summary>
        /// Flattens the request payload if the number of properties of the 
        /// payload is less than or equal to the PayloadFlatteningThreshold.
        /// </summary>
        /// <param name="serviceClient">Service client</param>                            
        /// <param name="settings">AutoRest settings</param>                            
        public static void FlattenRequestPayload(ServiceClient serviceClient, Settings settings)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException("serviceClient");    
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            foreach (var method in serviceClient.Methods)
            {
                var bodyParameter = method.Parameters.FirstOrDefault(
                    p => p.Location == ParameterLocation.Body);

                if (bodyParameter != null)
                {
                    var bodyParameterType = bodyParameter.Type as CompositeType;
                    if (bodyParameterType != null && bodyParameterType.ComposedProperties.Count(p => !p.IsConstant) <= settings.PayloadFlatteningThreshold)
                    {
                        var parameterTransformation = new ParameterTransformation
                        {
                            OutputParameter = bodyParameter
                        };
                        method.InputParameterTransformation.Add(parameterTransformation);

                        foreach (var property in bodyParameterType.ComposedProperties.Where(p => !p.IsConstant))
                        {
                            var newMethodParameter = new Parameter();
                            newMethodParameter.LoadFrom(property);
                            method.Parameters.Add(newMethodParameter);

                            parameterTransformation.ParameterMappings.Add(new ParameterMapping
                            {
                                InputParameter = newMethodParameter,
                                OutputParameterProperty = property.Name
                            });
                        }

                        method.Parameters.Remove(bodyParameter);
                    }
                }
            }
        }
コード例 #16
0
ファイル: CodeGenerator.cs プロジェクト: xingwu1/autorest
 protected CodeGenerator(Settings settings)
 {
     Settings = settings;
 }
コード例 #17
0
 public NodeJSCodeGenerator(Settings settings) : base(settings)
 {
     Namer = new NodeJsCodeNamer();
 }