public string GetModelsRequiredFiles()
        {
            var sb = new IndentedStringBuilder();

            this.GetOrderedModels().Where(m => !m.Extensions.ContainsKey(ExternalExtension)).ForEach(model => sb.AppendLine("{0}",
                this.GetRequiredFormat("models/" + RubyCodeNamer.UnderscoreCase(model.Name) + ".rb")));

            this.EnumTypes.ForEach(enumType => sb.AppendLine(this.GetRequiredFormat("models/" + RubyCodeNamer.UnderscoreCase(enumType.Name) + ".rb")));

            return sb.ToString();
        }
        /// <summary>
        /// Generates Ruby code in form of string for deserializing polling response.
        /// </summary>
        /// <param name="variableName">Variable name which keeps the response.</param>
        /// <param name="type">Type of response.</param>
        /// <returns>Ruby code in form of string for deserializing polling response.</returns>
        public string DeserializePollingResponse(string variableName, IType type)
        {
            var builder = new IndentedStringBuilder("  ");

            string serializationLogic = type.DeserializeType(this.Scope, variableName);
            return builder.AppendLine(serializationLogic).ToString();
        }
 public override string ConstructModelMapper()
 {
     var modelMapper = this.ConstructMapper(SerializedName, null, true, true);
     var builder = new IndentedStringBuilder("  ");
     builder.AppendLine("return {{{0}}};", modelMapper);
     return builder.ToString();
 }
        /// <summary>
        /// Generates code for model deserialization.
        /// </summary>
        /// <param name="variableName">Variable deserialize model from.</param>
        /// <param name="type">The type of the model.</param>
        /// <returns>The code for вуserialization in string format.</returns>
        public override string DeserializeProperty(string variableName, IType type)
        {
            var builder = new IndentedStringBuilder("  ");

            string serializationLogic = type.AzureDeserializeType(this.Scope, variableName);
            return builder.AppendLine(serializationLogic).ToString();
        }
 public string GetOperationsRequiredFiles()
 {
     var sb = new IndentedStringBuilder();
     this.MethodGroups.ForEach(method => sb.AppendLine("{0}",
         this.GetRequiredFormat(RubyCodeNamer.UnderscoreCase(method) + ".rb")));
     return sb.ToString();
 }
 protected override void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false)
 {
     if (this.InputParameterTransformation.IsNullOrEmpty())
     {
         return;
     }
     var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
     var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter;
     if (nextGroupType.Name == groupedType.Name)
     {
         return;
     }
     var nextGroupTypeName = _namer.GetTypeName(nextGroupType.Name) + "Inner";
     if (filterRequired && !nextGroupType.IsRequired)
     {
         return;
     }
     if (!groupedType.IsRequired)
     {
         builder.AppendLine("{0} {1} = null;", nextGroupTypeName, nextGroupType.Name.ToCamelCase());
         builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase());
         builder.Indent();
         builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
     }
     else
     {
         builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName);
     }
     foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter))
     {
         builder.AppendLine("{0}.with{1}({2}.{3}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase(), outParam.Name.ToCamelCase());
     }
     if (!groupedType.IsRequired)
     {
         builder.Outdent().AppendLine(@"}");
     }
 }
        public void AppendMultilinePreservesIndentation()
        {
            IndentedStringBuilder sb = new IndentedStringBuilder();
            var expected = string.Format("start{0}    line2{0}        line31{0}        line32{0}", Environment.NewLine);
            var result = sb
                .AppendLine("start").Indent()
                    .AppendLine("line2").Indent()
                    .AppendLine(string.Format("line31{0}line32", Environment.NewLine));
            Assert.Equal(expected, result.ToString());

            sb = new IndentedStringBuilder();
            expected = string.Format("start{0}    line2{0}        line31{0}        line32{0}", Environment.NewLine);
            result = sb
                .AppendLine("start").Indent()
                    .AppendLine("line2").Indent()
                    .AppendLine(string.Format("line31{0}line32", Environment.NewLine));
            Assert.Equal(expected, result.ToString());
        }
        public void AppendMultilinePreservesIndentation()
        {
            IndentedStringBuilder sb = new IndentedStringBuilder();
            var expected = "start\r\n    line2\r\n        line31\n        line32\r\n";
            var result = sb
                .AppendLine("start").Indent()
                    .AppendLine("line2").Indent()
                    .AppendLine("line31\nline32");
            Assert.Equal(expected, result.ToString());

            sb = new IndentedStringBuilder();
            expected = "start\r\n    line2\r\n        line31\r\n        line32\r\n";
            result = sb
                .AppendLine("start").Indent()
                    .AppendLine("line2").Indent()
                    .AppendLine("line31\r\nline32");
            Assert.Equal(expected, result.ToString());
        }
        public virtual string AddIndividualResponseHeader(HttpStatusCode? code)
        {
            IType 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();
        }
 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;
     }
 }
        public virtual string BuildUrlPath(string variableName)
        {
            var builder = new IndentedStringBuilder("    ");

            var pathParameterList = this.LogicalParameters.Where(p => p.Location == ParameterLocation.Path).ToList();
            if (pathParameterList.Any())
            {
                builder.AppendLine("path_format_arguments = {").Indent();

                for (int i = 0; i < pathParameterList.Count; i ++)
                {
                    builder.AppendLine("'{0}': {1}{2}{3}",
                        pathParameterList[i].SerializedName,
                        BuildSerializeDataCall(pathParameterList[i], "url"),
                        pathParameterList[i].IsRequired ? string.Empty :
                            string.Format(CultureInfo.InvariantCulture, "if {0} else ''", pathParameterList[i].Name),
                        i == pathParameterList.Count-1 ? "" : ",");
                }

                builder.Outdent().AppendLine("}");
                builder.AppendLine("{0} = {0}.format(**path_format_arguments)", variableName);
            }

            return builder.ToString();
        }
 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();
 }
        /// <summary>
        /// Genrate code to build an array of query parameter strings in a variable named 'queryParameters'.  The 
        /// array should contain one string element for each query parameter of the form 'key=value'
        /// </summary>
        /// <param name="builder">The stringbuilder for url construction</param>
        protected virtual void BuildQueryParameterArray(IndentedStringBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            builder.AppendLine("var queryParameters = [];");
            foreach (var queryParameter in LogicalParameters
                .Where(p => p.Location == ParameterLocation.Query))
            {
                var queryAddFormat = "queryParameters.push('{0}=' + encodeURIComponent({1}));";
                if (queryParameter.SkipUrlEncoding())
                {
                    queryAddFormat = "queryParameters.push('{0}=' + {1});";
                }
                if (!queryParameter.IsRequired)
                {
                    builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", queryParameter.Name)
                        .Indent()
                        .AppendLine(queryAddFormat,
                            queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue()).Outdent()
                        .AppendLine("}");
                }
                else
                {
                    builder.AppendLine(queryAddFormat,
                        queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue());
                }
            }
        }
        /// <summary>
        /// Generate code to remove duplicated forward slashes from a URL in code
        /// </summary>
        /// <param name="urlVariableName"></param>
        /// <returns></returns>
        public virtual string RemoveDuplicateForwardSlashes(string urlVariableName)
        {
            var builder = new IndentedStringBuilder("  ");

            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();
        }
 public static string ConstructPropertyDocumentation(string propertyDocumentation)
 {
     var builder = new IndentedStringBuilder("  ");
     return builder.AppendLine(propertyDocumentation)
                   .AppendLine(" * ").ToString();
 }
        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();
        }
 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();
 }
        /// <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();

            foreach (var pathParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Path))
            {
                builder.AppendLine("{0} = {0}.Replace(\"{{{1}}}\", Uri.EscapeDataString({2}));",
                    variableName,
                    pathParameter.SerializedName,
                    pathParameter.Type.ToString(ClientReference, pathParameter.Name));
            }
            if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query))
            {
                builder.AppendLine("List<string> _queryParameters = new List<string>();");
                foreach (var queryParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Query))
                {
                    builder.AppendLine("if ({0} != null)", queryParameter.Name)
                        .AppendLine("{").Indent()
                        .AppendLine("_queryParameters.Add(string.Format(\"{0}={{0}}\", Uri.EscapeDataString({1})));",
                            queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference)).Outdent()
                        .AppendLine("}");
                }

                builder.AppendLine("if (_queryParameters.Count > 0)")
                    .AppendLine("{").Indent()
                    .AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName).Outdent()
                    .AppendLine("}");
            }

            return builder.ToString();
        }
        /// <summary>
        /// Generate code to replace path parameters in the url template with the appropriate values
        /// </summary>
        /// <param name="variableName">The variable name for the url to be constructed</param>
        /// <param name="builder">The string builder for url construction</param>
        protected virtual void BuildPathParameters(string variableName, IndentedStringBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path))
            {
                var pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', encodeURIComponent({2}));";
                if (pathParameter.SkipUrlEncoding())
                {
                    pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});";
                }
                builder.AppendLine(pathReplaceFormat, variableName, pathParameter.SerializedName,
                    pathParameter.Type.ToString(pathParameter.Name));
            }
        }
        /// <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 IType type, IScopeProvider scope, string valueReference, 
            Dictionary<Constraint, string> constraints)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            CompositeType model = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;

            var sb = new IndentedStringBuilder();

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

            if (constraints != null && constraints.Any())
            {
                AppendConstraintValidations(valueReference, constraints, sb);
            }

            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;
        }
 /// <summary>
 /// Generate code to construct the query string from an array of query parameter strings containing 'key=value'
 /// </summary>
 /// <param name="variableName">The variable reference for the url</param>
 /// <param name="builder">The string builder for url construction</param>
 private static void AddQueryParametersToUrl(string variableName, IndentedStringBuilder builder)
 {
     builder.AppendLine("if (queryParameters.length > 0) {")
         .Indent()
         .AppendLine("{0} += '?' + queryParameters.join('&');", variableName).Outdent()
         .AppendLine("}");
 }
 private static void AppendConstraintValidations(string valueReference, Dictionary<Constraint, string> constraints, IndentedStringBuilder sb)
 {
     foreach (var constraint in constraints.Keys)
     {
         string constraintCheck;
         string constraintValue = constraints[constraint];
         switch (constraint)
         {
             case Constraint.ExclusiveMaximum:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0} >= {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.ExclusiveMinimum:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0} <= {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.InclusiveMaximum:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0} > {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.InclusiveMinimum:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0} < {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.MaxItems:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0}.Count > {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.MaxLength:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0}.Length > {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.MinItems:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0}.Count < {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.MinLength:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0}.Length < {1}", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.MultipleOf:
                 constraintCheck = string.Format(CultureInfo.InvariantCulture, "{0} % {1} != 0", valueReference,
                     constraints[constraint]);
                 break;
             case Constraint.Pattern:
                 constraintValue = "\"" + constraintValue.Replace("\\", "\\\\") + "\"";
                 constraintCheck = string.Format(CultureInfo.InvariantCulture,
                     "!System.Text.RegularExpressions.Regex.IsMatch({0}, {1})", valueReference, constraintValue);
                 break;
             case Constraint.UniqueItems:
                 if ("true".Equals(constraints[constraint], StringComparison.OrdinalIgnoreCase))
                 {
                     constraintCheck = string.Format(CultureInfo.InvariantCulture,
                         "{0}.Count != {0}.Distinct().Count()", valueReference);
                 }
                 else
                 {
                     constraintCheck = null;
                 }
                 break;
             default:
                 throw new NotSupportedException("Constraint '" + constraint + "' is not supported.");
         }
         if (constraintCheck != null)
         {
             if (constraint != Constraint.UniqueItems)
             {
                 sb.AppendLine("if ({0})", constraintCheck)
                     .AppendLine("{").Indent()
                     .AppendLine("throw new ValidationException(ValidationRules.{0}, \"{1}\", {2});",
                         constraint, valueReference.Replace("this.", ""), constraintValue).Outdent()
                     .AppendLine("}");
             }
             else
             {
                 sb.AppendLine("if ({0})", constraintCheck)
                     .AppendLine("{").Indent()
                     .AppendLine("throw new ValidationException(ValidationRules.{0}, \"{1}\");",
                         constraint, valueReference.Replace("this.", "")).Outdent()
                     .AppendLine("}");
             }
         }
     }
 }
        /// <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>
        /// <returns>The code to validate the reference of the given type</returns>
        public static string ValidateType(this IType type, IScopeProvider scope, string valueReference)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            CompositeType model = type as CompositeType;
            SequenceType sequence = type as SequenceType;
            DictionaryType dictionary = type as DictionaryType;
            if (model != null && model.ShouldValidateChain())
            {
                return CheckNull(valueReference, string.Format(CultureInfo.InvariantCulture, 
                    "{0}.Validate();", valueReference));
            }
            if (sequence != null && sequence.ShouldValidateChain())
            {
                var elementVar = scope.GetVariableName("element");
                var innerValidation = sequence.ElementType.ValidateType(scope, elementVar);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    var sb = new IndentedStringBuilder();
                    sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference)
                        .AppendLine("{").Indent()
                            .AppendLine(innerValidation).Outdent()
                        .AppendLine("}");
                    return CheckNull(valueReference, sb.ToString());
                }
            }
            else if (dictionary != null && dictionary.ShouldValidateChain())
            {
                var valueVar = scope.GetVariableName("valueElement");
                var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar);
                if (!string.IsNullOrEmpty(innerValidation))
                {
                    var sb = new IndentedStringBuilder();
                    sb.AppendLine("if ({0} != null)", valueReference)
                        .AppendLine("{").Indent()
                            .AppendLine("foreach (var {0} in {1}.Values)",valueVar,valueReference)
                            .AppendLine("{").Indent()
                                .AppendLine(innerValidation).Outdent()
                            .AppendLine("}").Outdent()
                        .AppendLine("}");

                    return CheckNull(valueReference, sb.ToString());
                }
            }

            return null;
        }
 public static string ConstructParameterDocumentation(string documentation)
 {
     var builder = new IndentedStringBuilder("  ");
     return builder.AppendLine(documentation)
                   .AppendLine(" * ").ToString();
 }
        /// <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();
        }
        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))
                       .AppendLine("{").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();
        }
        protected void AddHeaderDictionary(IndentedStringBuilder builder, CompositeType headersType)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (headersType == null)
            {
                throw new ArgumentNullException("headersType");
            }

            foreach (var prop in headersType.Properties)
            {
                if (this.ServiceClient.EnumTypes.Contains(prop.Type))
                {
                    builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': models.{1},", prop.SerializedName, prop.Type.ToPythonRuntimeTypeString()));
                }
                else
                {
                    builder.AppendLine(String.Format(CultureInfo.InvariantCulture, "'{0}': '{1}',", prop.SerializedName, prop.Type.ToPythonRuntimeTypeString()));
                }
            }
        }
        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)
                {
                    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)
                    {
                        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 shouuld 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();
        }
        /// <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.Type is CompositeType)
                {
                    builder.AppendLine("{0} = models.{1}()",
                        transformation.OutputParameter.Name,
                        transformation.OutputParameter.Type.Name);
                }
                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();
        }
 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();
 }