コード例 #1
0
 public override string ConstructModelMapper()
 {
     var modelMapper = this.ConstructMapper(SerializedName, null, true, true);
     var builder = new IndentedStringBuilder("  ");
     builder.AppendLine("return {{{0}}};", modelMapper);
     return builder.ToString();
 }
コード例 #2
0
ファイル: MethodCsa.cs プロジェクト: asears/autorest
        /// <summary>
        /// Generate code to build the URL from a url expression and method parameters
        /// </summary>
        /// <param name="variableName">The variable to store the url in.</param>
        /// <returns></returns>
        public override string BuildUrl(string variableName)
        {
            var builder = new IndentedStringBuilder(IndentedStringBuilder.FourSpaces);

            ReplacePathParametersInUri(variableName, builder);
            AddQueryParametersToUri(variableName, builder);
            return(builder.ToString());
        }
コード例 #3
0
 public static string CheckNull(string valueReference, string executionBlock)
 {
     var sb = new IndentedStringBuilder();
     sb.AppendLine("if ({0} != null)", valueReference)
         .AppendLine("{").Indent()
             .AppendLine(executionBlock).Outdent()
         .AppendLine("}");
     return sb.ToString();
 }
コード例 #4
0
        /// <summary>
        /// Returns Ruby code as string which sets `next_method` property of the page with the respective next paging method
        /// and performs parameter re-assignment when required (ex. parameter grouping cases)
        /// </summary>
        public string AssignNextMethodToPage()
        {
            string            nextMethodName;
            Method            nextMethod        = null;
            PageableExtension pageableExtension = JsonConvert.DeserializeObject <PageableExtension>(Extensions[AzureExtensions.PageableExtension].ToString());

            // When pageable extension have operation name
            if (pageableExtension != null && !string.IsNullOrWhiteSpace(pageableExtension.OperationName))
            {
                nextMethod     = MethodGroup.Methods.FirstOrDefault(m => pageableExtension.OperationName.EqualsIgnoreCase(m.SerializedName));
                nextMethodName = nextMethod.Name;
            }
            // When pageable extension does not have operation name
            else
            {
                nextMethodName = (string)Extensions["nextMethodName"];
                nextMethod     = MethodGroup.Methods.FirstOrDefault(m => m.Name == nextMethodName);
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            // As there is no distinguishable property in next link parameter, we'll check to see whether any parameter contains "next" in the parameter name
            Parameter nextLinkParameter = nextMethod.Parameters.Where(p => ((string)p.Name).IndexOf("next", StringComparison.OrdinalIgnoreCase) >= 0).FirstOrDefault();

            builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "page.next_method = Proc.new do |{0}|", nextLinkParameter.Name));

            // In case of parmeter grouping, next methods parameter needs to be mapped with the origin methods parameter
            var origName = Singleton <CodeNamerRb> .Instance.UnderscoreCase(Name.RawValue);

            IEnumerable <Parameter> origMethodGroupedParameters = Parameters.Where(p => p.Name.Contains(origName));

            if (origMethodGroupedParameters.Any())
            {
                builder.Indent();
                foreach (Parameter param in nextMethod.Parameters)
                {
                    if (param.Name.Contains(nextMethod.Name) && (((string)param.Name.RawValue).Length > ((string)nextMethod.Name).Length)) //parameter that contains the method name + postfix, it's a grouped param
                    {
                        //assigning grouped parameter passed to the lazy method, to the parameter used in the invocation to the next method
                        string argumentName = ((string)param.Name).Replace(nextMethodName, origName);
                        builder.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0} = {1}", param.Name, argumentName));
                    }
                }
                builder.Outdent();
            }

            // Create AzureMethodTemplateModel from nextMethod to determine nextMethod's MethodParameterInvocation signature
            MethodRba nextMethodTemplateModel = New <MethodRba>().LoadFrom(nextMethod);

            builder.Indent().AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}_async({1})", nextMethodName, nextMethodTemplateModel.MethodParameterInvocation));
            builder.Outdent().Append(String.Format(CultureInfo.InvariantCulture, "end"));

            return(builder.ToString());
        }
コード例 #5
0
        /// <summary>
        /// Returns generated response or body of the auto-paginated method.
        /// </summary>
        public override string ResponseGeneration()
        {
            IndentedStringBuilder builder = new IndentedStringBuilder();

            if (ReturnType.Body != null)
            {
                if (ReturnType.Body is CompositeType)
                {
                    CompositeType compositeType = (CompositeType)ReturnType.Body;
                    if (compositeType.Extensions.ContainsKey(AzureExtensions.PageableExtension) && this.Extensions.ContainsKey("nextMethodName"))
                    {
                        bool isNextLinkMethod = this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"];
                        bool isPageable       = (bool)compositeType.Extensions[AzureExtensions.PageableExtension];
                        if (isPageable && !isNextLinkMethod)
                        {
                            builder.AppendLine("first_page = {0}_as_lazy({1})", Name, MethodParameterInvocation);
                            builder.AppendLine("first_page.get_all_items");
                            return(builder.ToString());
                        }
                    }
                }
            }
            return(base.ResponseGeneration());
        }
コード例 #6
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="type"/>.
        /// </summary>
        /// <param name="type">Type for which mapper being generated.</param>
        /// <param name="serializedName">Serialized name to be used.</param>
        /// <param name="parameter">Parameter of the composite type to construct the parameter constraints.</param>
        /// <param name="expandComposite">Expand composite type if <c>true</c> otherwise specify class_name in the mapper.</param>
        /// <returns>Mapper for the <paramref name="type"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// One of the example of the mapper is 
        /// {
        ///   required: false,
        ///   serialized_name: 'Fish',
        ///   type: {
        ///     name: 'Composite',
        ///     polymorphic_discriminator: 'fishtype',
        ///     uber_parent: 'Fish',
        ///     class_name: 'Fish',
        ///     model_properties: {
        ///       species: {
        ///         required: false,
        ///         serialized_name: 'species',
        ///         type: {
        ///           name: 'String'
        ///         }
        ///       },
        ///       length: {
        ///         required: true,
        ///         serialized_name: 'length',
        ///         type: {
        ///           name: 'Double'
        ///         }
        ///       },
        ///       siblings: {
        ///         required: false,
        ///         serialized_name: 'siblings',
        ///         type: {
        ///           name: 'Sequence',
        ///           element: {
        ///               required: false,
        ///               serialized_name: 'FishElementType',
        ///               type: {
        ///                 name: 'Composite',
        ///                 polymorphic_discriminator: 'fishtype',
        ///                 uber_parent: 'Fish',
        ///                 class_name: 'Fish'
        ///               }
        ///           }
        ///         }
        ///       }
        ///     }
        ///   }
        /// }
        /// </example>
        public static string ConstructMapper(this IModelType type, string serializedName, IVariable parameter, bool expandComposite)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var builder = new IndentedStringBuilder("  ");

            CompositeType composite = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            EnumType enumType = type as EnumType;
            if (enumType != null && enumType.ModelAsString)
            {
                primary = New<PrimaryType>(KnownPrimaryType.String);
            }
            builder.AppendLine("").Indent();

            builder.AppendLine(type.AddMetaData(serializedName, parameter));

            if (primary != null)
            {
                builder.AppendLine(primary.ContructMapperForPrimaryType());
            }
            else if (enumType != null && enumType.Name != null)
            {
                builder.AppendLine(((EnumTypeRb)enumType).ContructMapperForEnumType());
            }
            else if (sequence != null)
            {
                builder.AppendLine(sequence.ContructMapperForSequenceType());
            }
            else if (dictionary != null)
            {
                builder.AppendLine(dictionary.ContructMapperForDictionaryType());
            }
            else if (composite != null)
            {
                builder.AppendLine(composite.ContructMapperForCompositeType(expandComposite));
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} is not a supported Type.", type));
            }
            return builder.ToString();
        }
コード例 #7
0
        /// <summary>
        /// Generate code to build the URL from a url expression and method parameters
        /// </summary>
        /// <param name="variableName">The variable to store the url in.</param>
        /// <returns></returns>
        public virtual string BuildUrl(string variableName)
        {
            var builder = new IndentedStringBuilder("  ");
            BuildPathParameters(variableName, builder);
            RemoveDuplicateForwardSlashes("requestUrl", builder);
            if (HasQueryParameters())
            {
                BuildQueryParameterArray(builder);
                AddQueryParametersToUrl(variableName, builder);
            }

            return builder.ToString();
        }
コード例 #8
0
 public string GetDeserializationString(IType type, string valueReference = "result", string responseVariable = "parsedResponse")
 {
     var builder = new IndentedStringBuilder("  ");
     if (type is CompositeType)
     {
         builder.AppendLine("var resultMapper = new client.models['{0}']().mapper();", type.Name);
     }
     else
     {
         builder.AppendLine("var resultMapper = {{{0}}};", type.ConstructMapper(responseVariable, null, false, false));
     }
     builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
     return builder.ToString();
 }
コード例 #9
0
        public virtual string BuildFlattenParameterMappings()
        {
            var builder = new IndentedStringBuilder();
            foreach (var transformation in InputParameterTransformation)
            {
                builder.AppendLine("var {0};",
                        transformation.OutputParameter.Name);

                builder.AppendLine("if ({0}) {{", BuildNullCheckExpression(transformation))
                       .Indent();

                if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                    transformation.OutputParameter.Type is CompositeType)
                {
                    builder.AppendLine("{0} = new client.models['{1}']();",
                        transformation.OutputParameter.Name,
                        transformation.OutputParameter.Type.Name);
                }

                foreach (var mapping in transformation.ParameterMappings)
                {
                    builder.AppendLine("{0}{1};",
                        transformation.OutputParameter.Name,
                        mapping);
                }

                builder.Outdent()
                       .AppendLine("}");
            }

            return builder.ToString();
        }
コード例 #10
0
 /// <summary>
 /// Generates input mapping code block.
 /// </summary>
 /// <returns></returns>
 public virtual string BuildInputMappings()
 {
     var builder = new IndentedStringBuilder("  ");
     if (InputParameterTransformation.Count > 0)
     {
         if (AreWeFlatteningParameters())
         {
             return BuildFlattenParameterMappings();
         }
         else
         {
             return BuildGroupedParameterMappings();
         }
     }
     return builder.ToString();
 }
コード例 #11
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="composite"/>.
        /// </summary>
        /// <param name="composite">CompositeType for which mapper being generated.</param>
        /// <param name="expandComposite">Expand composite type if <c>true</c> otherwise specify class_name in the mapper.</param>
        /// <returns>Mapper for the <paramref name="composite"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for CompositeType.
        /// type: {
        ///   name: 'Composite',
        ///   polymorphic_discriminator: 'property_name',   -- name of the property for polymorphic discriminator
        ///                                                      Used only when x-ms-discriminator-value applied
        ///   uber_parent: 'parent_class_name',             -- name of the topmost level class on inheritance hierarchy
        ///                                                      Used only when x-ms-discriminator-value applied
        ///   class_name: 'class_name',                     -- name of the modeled class
        ///                                                      Used when <paramref name="expandComposite"/> is false
        ///   model_properties: {                           -- expanded properties of the model
        ///                                                      Used when <paramref name="expandComposite"/> is true
        ///     property_name : {                           -- name of the property of this composite type
        ///         ***                                     -- mapper of the IModelType from the type of the property
        ///     }
        ///   }
        /// }
        /// </example>
        private static string ContructMapperForCompositeType(this CompositeType composite, bool expandComposite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException(nameof(composite));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            builder.AppendLine("type: {").Indent()
                .AppendLine("name: 'Composite',");

            if (composite.IsPolymorphic)
            {
                builder.AppendLine("polymorphic_discriminator: '{0}',", composite.PolymorphicDiscriminator);
                var polymorphicType = composite;
                while (polymorphicType.BaseModelType != null)
                {
                    polymorphicType = polymorphicType.BaseModelType;
                }
                builder.AppendLine("uber_parent: '{0}',", polymorphicType.Name);
            }
            if (!expandComposite)
            {
                builder.AppendLine("class_name: '{0}'", composite.Name).Outdent().AppendLine("}");
            }
            else
            {
                builder.AppendLine("class_name: '{0}',", composite.Name)
                       .AppendLine("model_properties: {").Indent();

                // if the type is the base type, it doesn't get the the polymorphic discriminator here
                var composedPropertyList = composite.IsPolymorphic ? 
                    new List<Property>(composite.ComposedProperties.Where(each => !each.IsPolymorphicDiscriminator)) :
                    new List<Property>(composite.ComposedProperties);

                for (var i = 0; i < composedPropertyList.Count; i++)
                {
                    var prop = composedPropertyList[i];
                    var serializedPropertyName = prop.SerializedName.Value;

                    // This is a temporary fix until ms_rest serializtion client > 0.6.0 is released.
                    if (serializedPropertyName == "odata.nextLink")
                    {
                        serializedPropertyName = "odata\\\\.nextLink";
                    }

                    if (i != composedPropertyList.Count - 1)
                    {
                        builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false));
                    }
                    else
                    {
                        builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false));
                    }
                }
                // end of modelProperties and type
                builder.Outdent().
                    AppendLine("}").Outdent().
                    AppendLine("}");
            }

            return builder.ToString();
        }
コード例 #12
0
ファイル: MethodPy.cs プロジェクト: devigned/autorest
 public virtual string AddResponseHeader()
 {
     if (HasResponseHeader)
     {
         var builder = new IndentedStringBuilder("    ");
         builder.AppendLine("client_raw_response.add_headers(header_dict)");
         return builder.ToString();
     }
     else
     {
         return string.Empty;
     }
 }
コード例 #13
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="sequence"/>.
        /// </summary>
        /// <param name="sequence">SequenceType for which mapper being generated.</param>
        /// <returns>Mapper for the <paramref name="sequence"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for SequenceType.
        /// type: {
        ///   name: 'Sequence',
        ///   element: {
        ///     ***                                         -- mapper of the IModelType from the sequence element
        ///   }
        /// }
        /// </example>
        private static string ContructMapperForSequenceType(this SequenceType sequence)
        {
            if (sequence == null)
            {
                throw new ArgumentNullException(nameof(sequence));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            builder.AppendLine("type: {").Indent()
                     .AppendLine("name: 'Sequence',")
                     .AppendLine("element: {").Indent()
                     .AppendLine("{0}", sequence.ElementType.ConstructMapper(sequence.ElementType.Name + "ElementType", null, false)).Outdent()
                     .AppendLine("}").Outdent()
                     .AppendLine("}");

            return builder.ToString();
        }
コード例 #14
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="dictionary"/>.
        /// </summary>
        /// <param name="dictionary">DictionaryType for which mapper being generated.</param>
        /// <returns>Mapper for the <paramref name="dictionary"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for DictionaryType.
        /// type: {
        ///   name: 'Dictionary',
        ///   value: {
        ///     ***                                         -- mapper of the IModelType from the value type of dictionary
        ///   }
        /// }
        /// </example>
        private static string ContructMapperForDictionaryType(this DictionaryType dictionary)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException(nameof(dictionary));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            builder.AppendLine("type: {").Indent()
                .AppendLine("name: 'Dictionary',")
                .AppendLine("value: {").Indent()
                .AppendLine("{0}", dictionary.ValueType.ConstructMapper(dictionary.ValueType.Name + "ElementType", null, false)).Outdent()
                .AppendLine("}").Outdent()
                .AppendLine("}");

            return builder.ToString();
        }
コード例 #15
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="enumeration"/>.
        /// </summary>
        /// <param name="enumeration">EnumType for which mapper being generated.</param>
        /// <returns>Mapper for the <paramref name="enumeration"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for EnumType.
        /// type: {
        ///   name: 'Enum',
        ///   module: 'module_name'                         -- name of the module to be looked for enum values
        /// }
        /// </example>
        private static string ContructMapperForEnumType(this EnumTypeRb enumeration)
        {
            if (enumeration == null)
            {
                throw new ArgumentNullException(nameof(enumeration));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            builder.AppendLine("type: {").Indent()
                .AppendLine("name: 'Enum',")
                .AppendLine("module: '{0}'", enumeration.ModuleName).Outdent()
                .AppendLine("}");

            return builder.ToString();
        }
コード例 #16
0
        /// <summary>
        /// Constructs blueprint of the given <paramref name="primary"/>.
        /// </summary>
        /// <param name="primary">PrimaryType for which mapper being generated.</param>
        /// <returns>Mapper for the <paramref name="primary"/> as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for PrimaryType.
        /// type: {
        ///   name: 'Boolean'                               -- This value should be one of the KnownPrimaryType
        /// }
        /// </example>
        private static string ContructMapperForPrimaryType(this PrimaryType primary)
        {
            if (primary == null)
            {
                throw new ArgumentNullException(nameof(primary));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            if (primary.KnownPrimaryType == KnownPrimaryType.Boolean)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Double)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Double'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Int || primary.KnownPrimaryType == KnownPrimaryType.Long ||
                primary.KnownPrimaryType == KnownPrimaryType.Decimal)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.String || primary.KnownPrimaryType == KnownPrimaryType.Uuid)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Base64Url)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Date)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.DateTime)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.TimeSpan)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Object)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}");
            }
            else if (primary.KnownPrimaryType == KnownPrimaryType.Stream)
            {
                builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}");
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "{0} is not a supported primary Type for {1}.", primary.KnownPrimaryType, primary.SerializedName));
            }

            return builder.ToString();
        }
コード例 #17
0
        /// <summary>
        /// Adds metadata to the given <paramref name="type"/>.
        /// </summary>
        /// <param name="type">Type for which metadata being generated.</param>
        /// <param name="serializedName">Serialized name to be used.</param>
        /// <param name="parameter">Parameter of the composite type to construct the parameter constraints.</param>
        /// <returns>Metadata as string.</returns>
        /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception>
        /// <example>
        /// The below example shows possible mapper string for IParameter for IModelType.
        /// required: true | false,                         -- whether this property is required or not
        /// read_only: true | false,                        -- whether this property is read only or not. Default is false
        /// is_constant: true | false,                      -- whether this property is constant or not. Default is false
        /// serialized_name: 'name'                         -- serialized name of the property if provided
        /// default_value: 'value'                          -- default value of the property if provided
        /// constraints: {                                  -- constraints of the property
        ///   key: value,                                   -- constraint name and value if any
        ///   ***: *****
        /// }
        /// </example>
        private static string AddMetaData(this IModelType type, string serializedName, IVariable parameter)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

            Dictionary<Constraint, string> constraints = null;
            string defaultValue = null;
            bool isRequired = false;
            bool isConstant = false;
            bool isReadOnly = false;
            var property = parameter as Property;
            if (property != null)
            {
                isReadOnly = property.IsReadOnly;
            }
            if (parameter != null)
            {
                defaultValue = parameter.DefaultValue;
                isRequired = parameter.IsRequired;
                isConstant = parameter.IsConstant;
                constraints = parameter.Constraints;
            }

            CompositeType composite = type as CompositeType;
            if (composite != null && composite.ContainsConstantProperties && isRequired)
            {
                defaultValue = "{}";
            }

            if (isRequired)
            {
                builder.AppendLine("required: true,");
            }
            else
            {
                builder.AppendLine("required: false,");
            }
            if (isReadOnly)
            {
                builder.AppendLine("read_only: true,");
            }
            if (isConstant)
            {
                builder.AppendLine("is_constant: true,");
            }
            if (serializedName != null)
            {
                builder.AppendLine("serialized_name: '{0}',", serializedName);
            }
            if (defaultValue != null)
            {
                builder.AppendLine("default_value: {0},", defaultValue);
            }

            if (constraints != null && constraints.Count > 0)
            {
                builder.AppendLine("constraints: {").Indent();
                var keys = constraints.Keys.ToList<Constraint>();
                for (int j = 0; j < keys.Count; j++)
                {
                    var constraintValue = constraints[keys[j]];
                    if (keys[j] == Constraint.Pattern)
                    {
                        constraintValue = string.Format(CultureInfo.InvariantCulture, "'{0}'", constraintValue);
                    }
                    if (j != keys.Count - 1)
                    {
                        builder.AppendLine("{0}: {1},", keys[j], constraintValue);
                    }
                    else
                    {
                        builder.AppendLine("{0}: {1}", keys[j], constraintValue);
                    }
                }
                builder.Outdent()
                    .AppendLine("},");
            }

            return builder.ToString();
        }
コード例 #18
0
        public string ConstructImportTS()
        {
            IndentedStringBuilder builder = new IndentedStringBuilder(IndentedStringBuilder.TwoSpaces);
            builder.Append("import { ServiceClientOptions, RequestOptions, ServiceCallback");
            if (Properties.Any(p => p.Name.Equals("credentials", StringComparison.InvariantCultureIgnoreCase)))
            {
                builder.Append(", ServiceClientCredentials");
            }

            builder.Append(" } from 'ms-rest';");
            return builder.ToString();
        }
コード例 #19
0
ファイル: MethodPy.cs プロジェクト: devigned/autorest
        public virtual string AddIndividualResponseHeader(HttpStatusCode? code)
        {
            IModelType headersType = null;

            if (HasResponseHeader)
            {
                if (code != null)
                {
                    headersType = this.ReturnType.Headers;
                }
                else
                {
                    headersType = this.Responses[code.Value].Headers;
                }
            }

            var builder = new IndentedStringBuilder("    ");
            if (headersType == null)
            {
                if (code == null)
                {
                    builder.AppendLine("header_dict = {}");
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                builder.AppendLine("header_dict = {").Indent();
                AddHeaderDictionary(builder, (CompositeType)headersType);
                builder.Outdent().AppendLine("}");
            }
            return builder.ToString();
        }
コード例 #20
0
 public string ConstructTSItemTypeName()
 {
     var builder = new IndentedStringBuilder("  ");
     builder.AppendFormat("<{0}>", ClientModelExtensions.TSType(ItemType, true));
     return builder.ToString();
 }
コード例 #21
0
        /// <summary>
        /// Generate code to build the URL from a url expression and method parameters
        /// </summary>
        /// <param name="variableName">The variable to store the url in.</param>
        /// <returns></returns>
        public virtual string BuildUrl(string variableName)
        {
            var builder = new IndentedStringBuilder("  ");
            BuildPathParameters(variableName, builder);
            if (HasQueryParameters())
            {
                BuildQueryParameterArray(builder);
                AddQueryParametersToUrl(variableName, builder);
            }

            return builder.ToString();
        }
コード例 #22
0
ファイル: Extensions.cs プロジェクト: devigned/autorest
        public static string Fields(this CompositeType compositeType)
        {
            var indented = new IndentedStringBuilder("    ");
            var properties = compositeType.Properties;

            if (compositeType.BaseModelType != null)
            {
                indented.Append(compositeType.BaseModelType.Fields());
            }

            // If the type is a paged model type, ensure the nextLink field exists
            // Note: Inject the field into a copy of the property list so as to not pollute the original list
            if (    compositeType is ModelTemplateModel
                &&  !String.IsNullOrEmpty((compositeType as ModelTemplateModel).NextLink))
            {
                var nextLinkField = (compositeType as ModelTemplateModel).NextLink;
                foreach (Property p in properties) {
                    p.Name = GoCodeNamer.PascalCaseWithoutChar(p.Name, '.');
                    if (p.Name.Equals(nextLinkField, StringComparison.OrdinalIgnoreCase)) {
                        p.Name = nextLinkField;
                    }
                }
                if (!properties.Any(p => p.Name.Equals(nextLinkField, StringComparison.OrdinalIgnoreCase)))
                {
                    var property = new Property();
                    property.Name = nextLinkField;
                    property.Type = new PrimaryType(KnownPrimaryType.String) { Name = "string" };
                    properties = new List<Property>(properties);
                    properties.Add(property);
                }
            }

            // Emit each property, except for named Enumerated types, as a pointer to the type
            foreach (var property in properties)
            {
                EnumType enumType = property.Type as EnumType;
                if (enumType != null && enumType.IsNamed())
                {
                    indented.AppendFormat("{0} {1} {2}\n",
                                    property.Name,
                                    enumType.Name,
                                    property.JsonTag());

                }
                else if (property.Type is DictionaryType)
                {
                    indented.AppendFormat("{0} *{1} {2}\n", property.Name, (property.Type as MapType).FieldName, property.JsonTag());
                }
                else
                {
                    indented.AppendFormat("{0} *{1} {2}\n", property.Name, property.Type.Name, property.JsonTag());
                }
            }
            
            return indented.ToString();
        }
コード例 #23
0
        public static string ConstructMapper(this IType type, string serializedName, IParameter parameter, bool isPageable, bool expandComposite)
        {
            var builder = new IndentedStringBuilder("  ");
            string defaultValue = null;
            bool isRequired = false;
            bool isConstant = false;
            bool isReadOnly = false;
            Dictionary<Constraint, string> constraints = null;
            var property = parameter as Property;
            if (parameter != null)
            {
                defaultValue = parameter.DefaultValue;
                isRequired = parameter.IsRequired;
                isConstant = parameter.IsConstant;
                constraints = parameter.Constraints;
            }
            if (property != null)
            {
                isReadOnly = property.IsReadOnly;
            }
            CompositeType composite = type as CompositeType;
            if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired))
            {
                defaultValue = "{}";
            }
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            PrimaryType primary = type as PrimaryType;
            EnumType enumType = type as EnumType;
            builder.AppendLine("").Indent();
            if (isRequired)
            {
                builder.AppendLine("required: true,");
            }
            else
            {
                builder.AppendLine("required: false,");
            }
            if (isReadOnly)
            {
                builder.AppendLine("readOnly: true,");
            }
            if (isConstant)
            {
                builder.AppendLine("isConstant: true,");
            }
            if (serializedName != null)
            {
                builder.AppendLine("serializedName: '{0}',", serializedName);
            }
            if (defaultValue != null)
            {
                builder.AppendLine("defaultValue: {0},", defaultValue);
            }
            if (constraints != null && constraints.Count > 0)
            {
                builder.AppendLine("constraints: {").Indent();
                var keys = constraints.Keys.ToList<Constraint>();
                for (int j = 0; j < keys.Count; j++)
                {
                    var constraintValue = constraints[keys[j]];
                    if (keys[j] == Constraint.Pattern)
                    {
                        constraintValue = string.Format(CultureInfo.InvariantCulture, "'{0}'", constraintValue);
                    }
                    if (j != keys.Count - 1)
                    {
                        builder.AppendLine("{0}: {1},", keys[j], constraintValue);
                    }
                    else
                    {
                        builder.AppendLine("{0}: {1}", keys[j], constraintValue);
                    }
                }
                builder.Outdent().AppendLine("},");
            }
            // Add type information
            if (primary != null)
            {
                if (primary.Type == KnownPrimaryType.Boolean)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long ||
                    primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Double)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.String || primary.Type == KnownPrimaryType.Uuid)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Uuid)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Uuid'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.ByteArray)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Base64Url)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Date)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.DateTime)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.DateTimeRfc1123)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.TimeSpan)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.UnixTime)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Object)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}");
                }
                else if (primary.Type == KnownPrimaryType.Stream)
                {
                    builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}");
                }
                else
                {
                    throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidType, primary));
                }
            }
            else if (enumType != null)
            {
                builder.AppendLine("type: {")
                         .Indent()
                         .AppendLine("name: 'Enum',")
                         .AppendLine("allowedValues: {0}", enumType.GetEnumValuesArray())
                       .Outdent()
                       .AppendLine("}");
            }
            else if (sequence != null)
            {
                builder.AppendLine("type: {")
                         .Indent()
                         .AppendLine("name: 'Sequence',")
                         .AppendLine("element: {")
                           .Indent()
                           .AppendLine("{0}", sequence.ElementType.ConstructMapper(sequence.ElementType.Name + "ElementType", null, false, false))
                         .Outdent().AppendLine("}").Outdent().AppendLine("}");
            }
            else if (dictionary != null)
            {
                builder.AppendLine("type: {")
                         .Indent()
                         .AppendLine("name: 'Dictionary',")
                         .AppendLine("value: {")
                           .Indent()
                           .AppendLine("{0}", dictionary.ValueType.ConstructMapper(dictionary.ValueType.Name + "ElementType", null, false, false))
                         .Outdent().AppendLine("}").Outdent().AppendLine("}");
            }
            else if (composite != null)
            {
                builder.AppendLine("type: {")
                         .Indent()
                         .AppendLine("name: 'Composite',");
                if (composite.PolymorphicDiscriminator != null)
                {
                    builder.AppendLine("polymorphicDiscriminator: '{0}',", composite.PolymorphicDiscriminator);
                    var polymorphicType = composite;
                    while (polymorphicType.BaseModelType != null)
                    {
                        polymorphicType = polymorphicType.BaseModelType;
                    }
                    builder.AppendLine("uberParent: '{0}',", polymorphicType.Name);
                }
                if (!expandComposite)
                {
                    builder.AppendLine("className: '{0}'", composite.Name).Outdent().AppendLine("}");
                }
                else
                {
                    builder.AppendLine("className: '{0}',", composite.Name)
                           .AppendLine("modelProperties: {").Indent();
                    var composedPropertyList = new List<Property>(composite.ComposedProperties);
                    for (var i = 0; i < composedPropertyList.Count; i++)
                    {
                        var prop = composedPropertyList[i];
                        var serializedPropertyName = prop.SerializedName;
                        PropertyInfo nextLinkName = null;
                        string nextLinkNameValue = null;
                        if (isPageable)
                        {
                            var itemName = composite.GetType().GetProperty("ItemName");
                            nextLinkName = composite.GetType().GetProperty("NextLinkName");
                            nextLinkNameValue = (string)nextLinkName.GetValue(composite);
                            if (itemName != null && ((string)itemName.GetValue(composite) == prop.Name))
                            {
                                serializedPropertyName = "";
                            }

                            if (prop.Name.Contains("nextLink") && nextLinkName != null && nextLinkNameValue == null)
                            {
                                continue;
                            }
                        }

                        if (i != composedPropertyList.Count - 1)
                        {
                            if (!isPageable)
                            {
                                builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false, false));
                            }
                            else
                            {
                                // if pageable and nextlink is also present then we need a comma as nextLink would be the next one to be added
                                if (nextLinkNameValue != null)
                                {
                                    builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false, false));
                                }
                                else
                                {
                                    builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false, false));
                                }

                            }
                        }
                        else
                        {
                            builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.Type.ConstructMapper(serializedPropertyName, prop, false, false));
                        }
                    }
                    // end of modelProperties and type
                    builder.Outdent().AppendLine("}").Outdent().AppendLine("}");
                }
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidType, type));
            }
            return builder.ToString();
        }
コード例 #24
0
        public virtual string BuildGroupedParameterMappings()
        {
            var builder = new IndentedStringBuilder("  ");
            if (InputParameterTransformation.Count > 0)
            {
                // Declare all the output paramaters outside the try block
                foreach (var transformation in InputParameterTransformation)
                {
                    if (transformation.OutputParameter.Type is CompositeType &&
                        transformation.OutputParameter.IsRequired)
                    {
                        builder.AppendLine("var {0} = new client.models['{1}']();",
                            transformation.OutputParameter.Name,
                            transformation.OutputParameter.Type.Name);
                    }
                    else
                    {
                        builder.AppendLine("var {0};", transformation.OutputParameter.Name);
                    }

                }
                builder.AppendLine("try {").Indent();
                foreach (var transformation in InputParameterTransformation)
                {
                    builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation))
                           .AppendLine("{").Indent();
                    var outputParameter = transformation.OutputParameter;
                    bool noCompositeTypeInitialized = true;
                    if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                        transformation.OutputParameter.Type is CompositeType)
                    {
                        //required outputParameter is initialized at the time of declaration
                        if (!transformation.OutputParameter.IsRequired)
                        {
                            builder.AppendLine("{0} = new client.models['{1}']();",
                                transformation.OutputParameter.Name,
                                transformation.OutputParameter.Type.Name);
                        }

                        noCompositeTypeInitialized = false;
                    }

                    foreach (var mapping in transformation.ParameterMappings)
                    {
                        builder.AppendLine("{0}{1};",
                            transformation.OutputParameter.Name,
                            mapping);
                        if (noCompositeTypeInitialized)
                        {
                            // If composite type is initialized based on the above logic then it should not be validated.
                            builder.AppendLine(outputParameter.Type.ValidateType(Scope, outputParameter.Name, outputParameter.IsRequired));
                        }
                    }

                    builder.Outdent()
                           .AppendLine("}");
                }
                builder.Outdent()
                       .AppendLine("} catch (error) {")
                         .Indent()
                         .AppendLine("return callback(error);")
                       .Outdent()
                       .AppendLine("}");
            }
            return builder.ToString();
        }
コード例 #25
0
        private static string ValidateCompositeType(IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();
            //Only validate whether the composite type is present, if it is required. Detailed validation happens in serialization.
            if (isRequired)
            {
                builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference)
                         .Indent()
                         .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference)
                       .Outdent()
                       .AppendLine("}");
            }
            return builder.ToString();
        }
コード例 #26
0
 public string BuildOptionalMappings()
 {
     IEnumerable<Property> optionalParameters =
         ((CompositeType)OptionsParameterTemplateModel.Type)
         .Properties.Where(p => p.Name != "customHeaders");
     var builder = new IndentedStringBuilder("  ");
     foreach (var optionalParam in optionalParameters)
     {
         string defaultValue = "undefined";
         if (!string.IsNullOrWhiteSpace(optionalParam.DefaultValue))
         {
             defaultValue = optionalParam.DefaultValue;
         }
         builder.AppendLine("var {0} = ({1} && {1}.{2} !== undefined) ? {1}.{2} : {3};",
             optionalParam.Name, OptionsParameterTemplateModel.Name, optionalParam.Name, defaultValue);
     }
     return builder.ToString();
 }
コード例 #27
0
ファイル: MethodPy.cs プロジェクト: devigned/autorest
        /// <summary>
        /// Generate code to build the headers from method parameters
        /// </summary>
        /// <param name="variableName">The variable to store the headers in.</param>
        /// <returns></returns>
        public virtual string BuildHeaders(string variableName)
        {
            var builder = new IndentedStringBuilder("    ");

            foreach (var headerParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Header))
            {
                if (headerParameter.IsRequired)
                {
                    builder.AppendLine("{0}['{1}'] = {2}",
                            variableName,
                            headerParameter.SerializedName,
                            BuildSerializeDataCall(headerParameter, "header"));
                }
                else
                {
                    builder.AppendLine("if {0} is not None:", headerParameter.Name)
                        .Indent()
                        .AppendLine("{0}['{1}'] = {2}", 
                            variableName,
                            headerParameter.SerializedName,
                            BuildSerializeDataCall(headerParameter, "header"))
                        .Outdent();
                }
            }

            return builder.ToString();
        }
コード例 #28
0
        public string DeserializeResponse(IType type, string valueReference = "result", string responseVariable = "parsedResponse")
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var builder = new IndentedStringBuilder("  ");
            builder.AppendLine("var {0} = null;", responseVariable)
                   .AppendLine("try {")
                   .Indent()
                     .AppendLine("{0} = JSON.parse(responseBody);", responseVariable)
                     .AppendLine("{0} = JSON.parse(responseBody);", valueReference);
            var deserializeBody = GetDeserializationString(type, valueReference, responseVariable);
            if (!string.IsNullOrWhiteSpace(deserializeBody))
            {
                builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable)
                         .Indent()
                         .AppendLine(deserializeBody)
                       .Outdent()
                       .AppendLine("}");
            }
            builder.Outdent()
                   .AppendLine("} catch (error) {")
                     .Indent()
                     .AppendLine(DeserializationError)
                   .Outdent()
                   .AppendLine("}");

            return builder.ToString();
        }
コード例 #29
0
ファイル: PageTemplateModel.cs プロジェクト: haocs/autorest
 public string ConstructTSItemTypeName()
 {
     var builder = new IndentedStringBuilder("  ");
     builder.AppendFormat("<{0}>", ItemType.Name);
     return builder.ToString();
 }
コード例 #30
0
 /// <summary>
 /// Generate code to remove duplicated forward slashes from a URL in code
 /// </summary>
 /// <param name="urlVariableName"></param>
 /// <param name="builder">The stringbuilder for url construction</param>
 /// <returns></returns>
 public virtual string RemoveDuplicateForwardSlashes(string urlVariableName, IndentedStringBuilder builder)
 {
     builder.AppendLine("// trim all duplicate forward slashes in the url");
     builder.AppendLine("var regex = /([^:]\\/)\\/+/gi;");
     builder.AppendLine("{0} = {0}.replace(regex, '$1');", urlVariableName);
     return builder.ToString();
 }
コード例 #31
0
        /// <summary>
        /// Generate code to perform required validation on a type
        /// </summary>
        /// <param name="type">The type to validate</param>
        /// <param name="scope">A scope provider for generating variable names as necessary</param>
        /// <param name="valueReference">A reference to the value being validated</param>
        /// <param name="constraints">Constraints</param>
        /// <returns>The code to validate the reference of the given type</returns>
        public static string ValidateType(this IModelType type, IChild scope, string valueReference, 
            Dictionary<Constraint, string> constraints)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var model = type as CompositeTypeCs;
            var sequence = type as SequenceTypeCs;
            var dictionary = type as DictionaryTypeCs;

            var sb = new IndentedStringBuilder();

            if (model != null && model.ShouldValidateChain())
            {
                sb.AppendLine("{0}.Validate();", valueReference);
            }

            if (constraints != null && constraints.Any())
            {
                AppendConstraintValidations(valueReference, constraints, sb, (type as PrimaryType)?.KnownFormat ?? KnownFormat.none);
            }

            if (sequence != null && sequence.ShouldValidateChain())
            {
                var elementVar = scope.GetUniqueName("element");
                var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference)
                       .AppendLine("{").Indent()
                           .AppendLine(innerValidation).Outdent()
                       .AppendLine("}");
                }
            }
            else if (dictionary != null && dictionary.ShouldValidateChain())
            {
                var valueVar = scope.GetUniqueName("valueElement");
                var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference)
                      .AppendLine("{").Indent()
                          .AppendLine(innerValidation).Outdent()
                      .AppendLine("}").Outdent();
                }
            }

            if (sb.ToString().Trim().Length > 0)
            {
                if (type.IsValueType())
                {
                    return sb.ToString();
                }
                else
                {
                    return CheckNull(valueReference, sb.ToString());
                }
            }

            return null;
        }
コード例 #32
0
        private static string ValidateEnumType(this EnumType enumType, IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var allowedValues = scope.GetUniqueName("allowedValues");

            builder.AppendLine("if ({0}) {{", valueReference)
                        .Indent()
                            .AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray())
                            .AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, valueReference)
                            .Indent()
                                .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", valueReference, allowedValues)
                            .Outdent()
                            .AppendLine("}");
            if (isRequired)
            {
                var escapedValueReference = valueReference.EscapeSingleQuotes();
                builder.Outdent().AppendLine("} else {")
                    .Indent()
                        .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference)
                    .Outdent()
                    .AppendLine("}");
            }
            else
            {
                builder.Outdent().AppendLine("}");
            }

            return builder.ToString();
        }
コード例 #33
0
ファイル: MethodPy.cs プロジェクト: devigned/autorest
        /// <summary>
        /// Generates input mapping code block.
        /// </summary>
        /// <returns></returns>
        public virtual string BuildInputMappings()
        {
            var builder = new IndentedStringBuilder("    ");
            foreach (var transformation in InputParameterTransformation)
            {
                if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                    transformation.OutputParameter.ModelType is CompositeType)
                {
                    var comps = CodeModel.ModelTypes.Where(x => x.Name == transformation.OutputParameter.ModelTypeName);
                    var composite = comps.First();

                    List<string> combinedParams = new List<string>();
                    List<string> paramCheck = new List<string>();

                    foreach (var mapping in transformation.ParameterMappings)
                    {
                        // var mappedParams = composite.ComposedProperties.Where(x => x.Name.RawValue == mapping.InputParameter.Name.RawValue);
                        var mappedParams = composite.ComposedProperties.Where(x => x.Name == mapping.InputParameter.Name);
                        if (mappedParams.Any())
                        {
                            var param = mappedParams.First();
                            combinedParams.Add(string.Format(CultureInfo.InvariantCulture, "{0}={0}", param.Name));
                            paramCheck.Add(string.Format(CultureInfo.InvariantCulture, "{0} is not None", param.Name));
                        }
                    }

                    if (!transformation.OutputParameter.IsRequired)
                    {
                        builder.AppendLine("{0} = None", transformation.OutputParameter.Name);
                        builder.AppendLine("if {0}:", string.Join(" or ", paramCheck)).Indent();
                    }
                    builder.AppendLine("{0} = models.{1}({2})",
                        transformation.OutputParameter.Name,
                        transformation.OutputParameter.ModelType.Name,
                        string.Join(", ", combinedParams));
                }
                else
                {
                    builder.AppendLine("{0} = None",
                            transformation.OutputParameter.Name);
                    builder.AppendLine("if {0}:", BuildNullCheckExpression(transformation))
                       .Indent();
                    foreach (var mapping in transformation.ParameterMappings)
                    {
                        builder.AppendLine("{0}{1}",
                            transformation.OutputParameter.Name,
                            mapping);
                    }
                    builder.Outdent();
                }
            }

            return builder.ToString();
        }