Exemple #1
0
        private void AddQueryParametersToUri(string variableName, IndentedStringBuilder builder)
        {
            builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();");
            if (LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query))
            {
                foreach (var queryParameter in LogicalParameterTemplateModels
                         .Where(p => p.Location == ParameterLocation.Query).Select(p => p as AzureParameterTemplateModel))
                {
                    string queryParametersAddString =
                        "_queryParameters.Add(string.Format(\"{0}={{0}}\", System.Uri.EscapeDataString({1})));";

                    if (queryParameter.IsODataFilterExpression)
                    {
                        queryParametersAddString = @"var _odataFilter = {2}.ToString();
    if (!string.IsNullOrEmpty(_odataFilter)) 
    {{
        _queryParameters.Add(_odataFilter);
    }}";
                    }
                    else if (queryParameter.Extensions.ContainsKey(AzureExtensions.SkipUrlEncodingExtension))
                    {
                        queryParametersAddString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", {1}));";
                    }

                    builder.AppendLine("if ({0} != null)", queryParameter.Name)
                    .AppendLine("{").Indent();

                    if (queryParameter.CollectionFormat == CollectionFormat.Multi)
                    {
                        builder.AppendLine("if ({0}.Count == 0)", queryParameter.Name)
                        .AppendLine("{").Indent()
                        .AppendLine(queryParametersAddString, queryParameter.SerializedName, "string.Empty").Outdent()
                        .AppendLine("}")
                        .AppendLine("else")
                        .AppendLine("{").Indent()
                        .AppendLine("foreach (var _item in {0})", queryParameter.Name)
                        .AppendLine("{").Indent()
                        .AppendLine(queryParametersAddString, queryParameter.SerializedName, "_item ?? string.Empty").Outdent()
                        .AppendLine("}").Outdent()
                        .AppendLine("}").Outdent();
                    }
                    else
                    {
                        builder.AppendLine(queryParametersAddString,
                                           queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference), queryParameter.Name);
                    }
                    builder.Outdent()
                    .AppendLine("}");
                }
            }

            builder.AppendLine("if (_queryParameters.Count > 0)")
            .AppendLine("{").Indent()
            .AppendLine("{0} += ({0}.Contains(\"?\") ? \"&\" : \"?\") + string.Join(\"&\", _queryParameters);", variableName).Outdent()
            .AppendLine("}");
        }
Exemple #2
0
        public string GetLongRunningOperationResponse(string clientReference)
        {
            var    builder   = new IndentedStringBuilder("  ");
            string lroOption = GetLROOptions();

            if (lroOption.Length == 0)
            {
                return(builder.AppendLine("{0}.get_long_running_operation_result(response, deserialize_method)", clientReference).ToString());
            }
            return(builder.AppendLine("{0}.get_long_running_operation_result(response, deserialize_method, {1})", clientReference, lroOption).ToString());
        }
Exemple #3
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());
        }
 public override string ConstructModelMapper()
 {
     var modelMapper = this.ConstructMapper(SerializedName, null, true, true);
     var builder = new IndentedStringBuilder("  ");
     builder.AppendLine("return {{{0}}};", modelMapper);
     return builder.ToString();
 }
Exemple #5
0
        /// <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, IModelType type)
        {
            var builder = new IndentedStringBuilder("  ");

            string serializationLogic = GetDeserializationString(type, variableName, variableName);

            return(builder.AppendLine(serializationLogic).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();
 }
Exemple #7
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());
        }
Exemple #8
0
        private void ReplacePathParametersInUri(string variableName, IndentedStringBuilder builder)
        {
            foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path))
            {
                string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));";
                if (pathParameter.Extensions.ContainsKey(AzureExtensions.SkipUrlEncodingExtension))
                {
                    replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});";
                }

                builder.AppendLine(replaceString,
                                   variableName,
                                   pathParameter.SerializedName,
                                   pathParameter.ModelType.ToString(ClientReference, pathParameter.Name));
            }
        }
        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());
        }
        private static string ValidateDictionaryType(this DictionaryType dictionary, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();
            var valueVar = scope.GetUniqueName("valueElement");
            var innerValidation = dictionary.ValueType.ValidateType(scope, valueReference + "[" + valueVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerValidation))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== 'object') {{", valueReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                            escapedValueReference, dictionary.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference)
                        .Indent()
                          .AppendLine(innerValidation)
                        .Outdent()
                      .AppendLine("}").ToString();
                }

                return builder.AppendLine("if ({0} && typeof {0} === 'object') {{", valueReference)
                        .Indent()
                          .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }
        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();
        }
        /// <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();
        }
        /// <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();
        }
 /// <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();
 }
        /// <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());
                }
            }
        }
 private static void AppendConstraintValidations(string valueReference, Dictionary<Constraint, string> constraints, IndentedStringBuilder sb, KnownFormat format)
 {
     foreach (var constraint in constraints.Keys)
     {
         string constraintCheck;
         string constraintValue = (format == KnownFormat.@char) ?$"'{constraints[constraint]}'" : constraints[constraint];
         switch (constraint)
         {
             case Constraint.ExclusiveMaximum:
                 constraintCheck = $"{valueReference} >= {constraintValue}";
                 break;
             case Constraint.ExclusiveMinimum:
                 constraintCheck = $"{valueReference} <= {constraintValue}";
                 break;
             case Constraint.InclusiveMaximum:
                 constraintCheck = $"{valueReference} > {constraintValue}";
                 break;
             case Constraint.InclusiveMinimum:
                 constraintCheck = $"{valueReference} < {constraintValue}";
                 break;
             case Constraint.MaxItems:
                 constraintCheck = $"{valueReference}.Count > {constraintValue}";
                 break;
             case Constraint.MaxLength:
                 constraintCheck = $"{valueReference}.Length > {constraintValue}";
                 break;
             case Constraint.MinItems:
                 constraintCheck = $"{valueReference}.Count < {constraintValue}";
                 break;
             case Constraint.MinLength:
                 constraintCheck = $"{valueReference}.Length < {constraintValue}";
                 break;
             case Constraint.MultipleOf:
                 constraintCheck = $"{valueReference} % {constraintValue} != 0";
                 break;
             case Constraint.Pattern:
                 constraintValue = $"\"{constraintValue.Replace("\\", "\\\\")}\"";
                 constraintCheck = $"!System.Text.RegularExpressions.Regex.IsMatch({valueReference}, {constraintValue})";
                 break;
             case Constraint.UniqueItems:
                 if ("true".EqualsIgnoreCase(constraints[constraint]))
                 {
                     constraintCheck = $"{valueReference}.Count != {valueReference}.Distinct().Count()";
                 }
                 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 Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\", {2});",
                         constraint, valueReference.Replace("this.", ""), constraintValue).Outdent()
                     .AppendLine("}");
             }
             else
             {
                 sb.AppendLine("if ({0})", constraintCheck)
                     .AppendLine("{").Indent()
                     .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\");",
                         constraint, valueReference.Replace("this.", "")).Outdent()
                     .AppendLine("}");
             }
         }
     }
 }
        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();
        }
Exemple #18
0
 public static string ConstructPropertyDocumentation(string propertyDocumentation)
 {
     var builder = new IndentedStringBuilder("  ");
     return builder.AppendLine(propertyDocumentation)
                   .AppendLine(" * ").ToString();
 }
        /// <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;
        }
        private static string ValidateSequenceType(this SequenceType sequence, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models")
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

            var builder = new IndentedStringBuilder("  ");
            var escapedValueReference = valueReference.EscapeSingleQuotes();

            var indexVar = scope.GetUniqueName("i");
            var innerValidation = sequence.ElementType.ValidateType(scope, valueReference + "[" + indexVar + "]", false, modelReference);
            if (!string.IsNullOrEmpty(innerValidation))
            {
                if (isRequired)
                {
                    return builder.AppendLine("if (!util.isArray({0})) {{", valueReference)
                        .Indent()
                          .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');",
                          escapedValueReference, sequence.Name.ToLower(CultureInfo.InvariantCulture))
                        .Outdent()
                      .AppendLine("}")
                      .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}").ToString();
                }

                return builder.AppendLine("if (util.isArray({0})) {{", valueReference)
                        .Indent()
                          .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar)
                            .Indent()
                              .AppendLine(innerValidation)
                            .Outdent()
                          .AppendLine("}")
                        .Outdent()
                      .AppendLine("}").ToString();
            }

            return null;
        }
        private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

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

            var builder = new IndentedStringBuilder("  ");
            var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');";
            var typeErrorMessage = "throw new Error('{0} must be of type {1}.');";
            var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture);
            if (primary.Type == KnownPrimaryType.Boolean ||
                primary.Type == KnownPrimaryType.Double ||
                primary.Type == KnownPrimaryType.Decimal ||
                primary.Type == KnownPrimaryType.Int ||
                primary.Type == KnownPrimaryType.Long ||
                primary.Type == KnownPrimaryType.Object)
            {
                if (isRequired)
                {
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.Stream)
            {
                if (isRequired)
                {
                    builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.String)
            {
                if (isRequired)
                {
                    //empty string can be a valid value hence we cannot implement the simple check if (!{0})
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.Uuid)
            {
                if (isRequired)
                {
                    requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type string and must be a valid {1}.');";
                    //empty string can be a valid value hence we cannot implement the simple check if (!{0})
                    builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== 'string' || !msRest.isValidUuid({0})) {{", valueReference);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }
                typeErrorMessage = "throw new Error('{0} must be of type string and must be a valid {1}.');";
                builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url)
            {
                if (isRequired)
                {
                    builder.AppendLine("if (!Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date ||
                primary.Type == KnownPrimaryType.DateTimeRfc1123 || primary.Type == KnownPrimaryType.UnixTime)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !({0} instanceof Date || ", valueReference)
                                                  .Indent()
                                                  .Indent()
                                                  .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder = builder.AppendLine("if ({0} && !({0} instanceof Date || ", valueReference)
                                              .Indent()
                                              .Indent()
                                              .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else if (primary.Type == KnownPrimaryType.TimeSpan)
            {
                if (isRequired)
                {
                    builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", valueReference);
                    return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString();
                }

                builder.AppendLine("if({0} && !moment.isDuration({0})) {{", valueReference);
                return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString();
            }
            else
            {
                throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture,
                    "'{0}' not implemented", valueReference));
            }
        }
        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();
        }
        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();
        }
 protected override void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false)
 {
     if (this.InputParameterTransformation.IsNullOrEmpty() || nextMethod.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 && !groupedType.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 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();
 }
        public static IndentedStringBuilder AppendConstraintValidations(this IType type, string valueReference, Dictionary<Constraint, string> constraints, 
            IndentedStringBuilder builder)
        {
            if (valueReference == null)
            {
                throw new ArgumentNullException("valueReference");
            }

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

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

            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}.length > {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}.length < {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,
                            "{0}.match({1}) === null", valueReference, constraintValue);
                        break;
                    case Constraint.UniqueItems:
                        if ("true".Equals(constraints[constraint], StringComparison.OrdinalIgnoreCase))
                        {
                            constraintCheck = string.Format(CultureInfo.InvariantCulture,
                                "{0}.length !== {0}.filter(function(item, i, ar) {{ return ar.indexOf(item) === i; }}).length", valueReference);
                        }
                        else
                        {
                            constraintCheck = null;
                        }
                        break;
                    default:
                        throw new NotSupportedException("Constraint '" + constraint + "' is not supported.");
                }
                if (constraintCheck != null)
                {
                    var escapedValueReference = valueReference.EscapeSingleQuotes();
                    if (constraint != Constraint.UniqueItems)
                    {
                        builder.AppendLine("if ({0})", constraintCheck)
                            .AppendLine("{").Indent()
                            .AppendLine("throw new Error('\"{0}\" should satisfy the constraint - \"{1}\": {2}');",
                                escapedValueReference, constraint, constraintValue).Outdent()
                            .AppendLine("}");
                    }
                    else
                    {
                        builder.AppendLine("if ({0})", constraintCheck)
                            .AppendLine("{").Indent()
                            .AppendLine("throw new Error('\"{0}\" should satisfy the constraint - \"{1}\"');",
                                escapedValueReference, constraint).Outdent()
                            .AppendLine("}");
                    }
                }
            }
            return builder;
        }
 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>
        /// Generates Ruby code in form of string for deserializing object of given type.
        /// </summary>
        /// <param name="type">Type of object needs to be deserialized.</param>
        /// <param name="scope">Current scope.</param>
        /// <param name="valueReference">Reference to object which needs to be deserialized.</param>
        /// <returns>Generated Ruby code in form of string.</returns>
        public static string AzureDeserializeType(
            this IModelType type,
            IChild scope,
            string valueReference)
        {
            var composite = type as CompositeType;
            var sequence = type as SequenceType;
            var dictionary = type as DictionaryType;
            var primary = type as PrimaryType;
            var enumType = type as EnumTypeRb;

            var builder = new IndentedStringBuilder("  ");

            if (primary != null)
            {
                if (primary.KnownPrimaryType == KnownPrimaryType.Int || primary.KnownPrimaryType == KnownPrimaryType.Long)
                {
                    return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.Double)
                {
                    return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray)
                {
                    return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.Date)
                {
                    return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTime)
                {
                    return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
                {
                    return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime)
                {
                    return builder.AppendLine("{0} = DateTime.strptime({0}.to_s, '%s') unless {0}.to_s.empty?", valueReference).ToString();
                }
            }
            else if (enumType != null && !string.IsNullOrEmpty(enumType.Name))
            {
                return builder
                    .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference)
                    .AppendLine(
                        "  enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}",
                        enumType.ModuleName, valueReference)
                    .AppendLine(
                        "  warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.ModuleName, valueReference)
                    .AppendLine("end")
                    .ToString();
            }
            else if (sequence != null)
            {
                var elementVar = scope.GetUniqueName("element");
                var innerSerialization = sequence.ElementType.AzureDeserializeType(scope, elementVar);

                if (!string.IsNullOrEmpty(innerSerialization))
                {
                    return
                        builder
                            .AppendLine("unless {0}.nil?", valueReference)
                                .Indent()
                                    .AppendLine("deserialized_{0} = []", sequence.Name.ToLower())
                                    .AppendLine("{0}.each do |{1}|", valueReference, elementVar)
                                    .Indent()
                                        .AppendLine(innerSerialization)
                                        .AppendLine("deserialized_{0}.push({1})", sequence.Name.ToLower(), elementVar)
                                    .Outdent()
                                    .AppendLine("end")
                                    .AppendLine("{0} = deserialized_{1}", valueReference, sequence.Name.ToLower())
                                .Outdent()
                            .AppendLine("end")
                            .ToString();
                }
            }
            else if (dictionary != null)
            {
                var valueVar = scope.GetUniqueName("valueElement");
                var innerSerialization = dictionary.ValueType.AzureDeserializeType(scope, valueVar);
                if (!string.IsNullOrEmpty(innerSerialization))
                {
                    return builder.AppendLine("unless {0}.nil?", valueReference)
                            .Indent()
                              .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar)
                                .Indent()
                                  .AppendLine(innerSerialization)
                                  .AppendLine("{0}[key] = {1}", valueReference, valueVar)
                               .Outdent()
                             .AppendLine("end")
                           .Outdent()
                         .AppendLine("end").ToString();
                }
            }
            else if (composite != null)
            {
                var compositeName = composite.Name;
                if(compositeName == "Resource" || compositeName == "SubResource")
                {
                    compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName);
                }
                return builder.AppendLine("unless {0}.nil?", valueReference)
                    .Indent()
                        .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, compositeName)
                    .Outdent()
                    .AppendLine("end").ToString();
            }

            return string.Empty;
        }
        /// <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});";
                }
                var urlPathName = pathParameter.SerializedName;
                string pat = @".*\{" + urlPathName + @"(\:\w+)\}";
                Regex r = new Regex(pat);
                Match m = r.Match(Url);
                if (m.Success)
                {
                    urlPathName += m.Groups[1].Value;
                }
                builder.AppendLine(pathReplaceFormat, variableName, urlPathName,
                    pathParameter.Type.ToString(pathParameter.Name));
            }
        }
        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();
        }
        /// <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 void AddQueryParametersToUrl(string variableName, IndentedStringBuilder builder)
        {
            builder.AppendLine("if (queryParameters.length > 0) {")
                .Indent();
            if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"])
            {
                builder.AppendLine("{0} += ({0}.indexOf('?') !== -1 ? '&' : '?') + queryParameters.join('&');", variableName);
            }
            else
            {
                builder.AppendLine("{0} += '?' + queryParameters.join('&');", variableName);
            }

            builder.Outdent().AppendLine("}");
        }
Exemple #32
0
        /////////////////////////////////////////////////////////////////////////////////////////
        //
        // Parameter Extensions
        //
        /////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Return a Go map of required parameters.
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="mapVariable"></param>
        /// <returns></returns>
        public static string BuildParameterMap(this IEnumerable<Parameter> parameters, string mapVariable)
        {
            var builder = new StringBuilder();

            builder.Append(mapVariable);
            builder.Append(" := map[string]interface{} {");

            if (parameters.Count() > 0)
            {
                builder.AppendLine();
                var indented = new IndentedStringBuilder("  ");
                parameters
                    .Where(p => p.IsRequired)
                    .OrderBy(p => p.SerializedName)
                    .ForEach(p => indented.AppendLine("\"{0}\": {1},", p.NameForMap(), p.ValueForMap()));
                builder.Append(indented);
            }
            builder.AppendLine("}");
            return builder.ToString();
        }
        /// <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();
        }
 public static string ConstructParameterDocumentation(string documentation)
 {
     var builder = new IndentedStringBuilder("  ");
     return builder.AppendLine(documentation)
                   .AppendLine(" * ").ToString();
 }
        /// <summary>
        /// Generates Ruby code in form of string for serializing object of given type.
        /// </summary>
        /// <param name="type">Type of object needs to be serialized.</param>
        /// <param name="scope">Current scope.</param>
        /// <param name="valueReference">Reference to object which needs to serialized.</param>
        /// <returns>Generated Ruby code in form of string.</returns>
        public static string AzureSerializeType(
            this IModelType type,
            IChild scope,
            string valueReference)
        {
            var composite = type as CompositeType;
            var sequence = type as SequenceType;
            var dictionary = type as DictionaryType;
            var primary = type as PrimaryType;

            var builder = new IndentedStringBuilder("  ");

            if (primary != null)
            {
                if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray)
                {
                    return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTime)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString();
                }

                if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime)
                {
                    return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%s')", valueReference).ToString();
                }
            }
            else if (sequence != null)
            {
                var elementVar = scope.GetUniqueName("element");
                var innerSerialization = sequence.ElementType.AzureSerializeType(scope, elementVar);

                if (!string.IsNullOrEmpty(innerSerialization))
                {
                    return
                        builder
                            .AppendLine("unless {0}.nil?", valueReference)
                                .Indent()
                                    .AppendLine("serialized{0} = []", sequence.Name)
                                    .AppendLine("{0}.each do |{1}|", valueReference, elementVar)
                                    .Indent()
                                        .AppendLine(innerSerialization)
                                        .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar)
                                    .Outdent()
                                    .AppendLine("end")
                                    .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase())
                                .Outdent()
                            .AppendLine("end")
                            .ToString();
                }
            }
            else if (dictionary != null)
            {
                var valueVar = scope.GetUniqueName("valueElement");
                var innerSerialization = dictionary.ValueType.AzureSerializeType(scope, valueVar);
                if (!string.IsNullOrEmpty(innerSerialization))
                {
                    return builder.AppendLine("unless {0}.nil?", valueReference)
                            .Indent()
                              .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar)
                                .Indent()
                                  .AppendLine(innerSerialization)
                                  .AppendLine("{0}[key] = {1}", valueReference, valueVar)
                               .Outdent()
                             .AppendLine("}")
                           .Outdent()
                         .AppendLine("end").ToString();
                }
            }
            else if (composite != null)
            {
                var compositeName = composite.Name;
                if(compositeName == "Resource" || compositeName == "SubResource")
                {
                    compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName);
                }
                return builder.AppendLine("unless {0}.nil?", valueReference)
                    .Indent()
                        .AppendLine("{0} = {1}.serialize_object({0})", valueReference, compositeName)
                    .Outdent()
                    .AppendLine("end").ToString();
            }

            return string.Empty;
        }
        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();
        }