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

            IndentedStringBuilder builder = new IndentedStringBuilder("  ");

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

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

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

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

            return builder.ToString();
        }
        /// <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 IType 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.PolymorphicDiscriminator != null)
            {
                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();
                var composedPropertyList = new List<Property>(composite.ComposedProperties);
                for (var i = 0; i < composedPropertyList.Count; i++)
                {
                    var prop = composedPropertyList[i];
                    var serializedPropertyName = prop.SerializedName;

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

            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("}");
        }
        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();
        }
        /// <summary>
        /// Build parameter mapping from parameter grouping transformation.
        /// </summary>
        /// <returns></returns>
        public virtual string BuildInputParameterMappings()
        {
            var builder = new IndentedStringBuilder("  ");
            if (InputParameterTransformation.Count > 0)
            {
                builder.Indent();
                foreach (var transformation in InputParameterTransformation)
                {
                    if (transformation.OutputParameter.Type is CompositeType &&
                        transformation.OutputParameter.IsRequired)
                    {
                        builder.AppendLine("{0} = {1}.new",
                            transformation.OutputParameter.Name,
                            transformation.OutputParameter.Type.Name);
                    }
                    else
                    {
                        builder.AppendLine("{0} = nil", transformation.OutputParameter.Name);
                    }
                }
                foreach (var transformation in InputParameterTransformation)
                {
                    builder.AppendLine("unless {0}", BuildNullCheckExpression(transformation))
                           .AppendLine().Indent();
                    var outputParameter = transformation.OutputParameter;
                    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} = {1}.new",
                                transformation.OutputParameter.Name,
                                transformation.OutputParameter.Type.Name);
                        }
                    }

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

                    builder.Outdent().AppendLine("end");
                }
            }
            return builder.ToString();
        }
        private void AddQueryParametersToUri(string variableName, IndentedStringBuilder builder)
        {
            builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();");
            if (LogicalParameters.Any(p => p.Location == ParameterLocation.Query))
            {
                foreach (var queryParameter in LogicalParameters
                    .Where(p => p.Location == ParameterLocation.Query).Select(p => p as ParameterCsa))
                {
                    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("}");
        }
        /// <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))
            {
                string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));";
                if (pathParameter.SkipUrlEncoding())
                {
                    replaceString = "{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;
                }
                if (pathParameter.Type is SequenceType)
                {
                    builder.AppendLine(replaceString,
                    variableName,
                    urlPathName,
                    pathParameter.GetFormattedReferenceValue(ClientReference));
                }
                else
                {
                    builder.AppendLine(replaceString,
                    variableName,
                    urlPathName,
                    pathParameter.Type.ToString(ClientReference, pathParameter.Name));
                }
            }
            if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query))
            {
                builder.AppendLine("System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();");
                foreach (var queryParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Query))
                {
                    var replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", System.Uri.EscapeDataString({1})));";
                    if (queryParameter.CanBeNull())
                    {
                        builder.AppendLine("if ({0} != null)", queryParameter.Name)
                            .AppendLine("{").Indent();
                    }

                    if(queryParameter.SkipUrlEncoding())
                    {
                        replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", {1}));";
                    }

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

                    if (queryParameter.CanBeNull())
                    {
                        builder.Outdent()
                            .AppendLine("}");
                    }
                }

                builder.AppendLine("if (_queryParameters.Count > 0)")
                    .AppendLine("{").Indent();
                if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"])
                {
                    builder.AppendLine("{0} += ({0}.Contains(\"?\") ? \"&\" : \"?\") + string.Join(\"&\", _queryParameters);", variableName);
                }
                else
                {
                    builder.AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName);
                }

                builder.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)
            {
                var compositeOutputParameter = transformation.OutputParameter.Type as CompositeType;
                if (transformation.OutputParameter.IsRequired && compositeOutputParameter != null)
                {
                    builder.AppendLine("{0} {1} = new {0}();",
                        transformation.OutputParameter.Type.Name,
                        transformation.OutputParameter.Name);
                }
                else
                {
                    builder.AppendLine("{0} {1} = default({0});",
                        transformation.OutputParameter.Type.Name,
                        transformation.OutputParameter.Name);
                }
                var nullCheck = BuildNullCheckExpression(transformation);
                if (!string.IsNullOrEmpty(nullCheck))
                {
                    builder.AppendLine("if ({0})", nullCheck)
                       .AppendLine("{").Indent();
                }

                if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                    compositeOutputParameter != null && !transformation.OutputParameter.IsRequired)
                {
                    builder.AppendLine("{0} = new {1}();",
                        transformation.OutputParameter.Name,
                        transformation.OutputParameter.Type.Name);
                }

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

                if (!string.IsNullOrEmpty(nullCheck))
                {
                    builder.Outdent()
                       .AppendLine("}");
                }
            }

            return builder.ToString();
        }
 public override string SuccessCallback(bool filterRequired = false)
 {
     if (this.IsPagingOperation)
     {
         var builder = new IndentedStringBuilder();
         builder.AppendLine("{0} result = {1}Delegate(response);",
             ReturnTypeModel.WireResponseTypeString, this.Name);
         builder.AppendLine("if (serviceCallback != null) {").Indent();
         builder.AppendLine("serviceCallback.load(result.getBody().getItems());");
         builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent()
             .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent();
         string invocation;
         AzureMethodTemplateModel nextMethod = GetPagingNextMethodWithInvocation(out invocation, true);
         TransformPagingGroupedParameter(builder, nextMethod, filterRequired);
         var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.getBody().getNextPageLink(), {1});",
             invocation,
             filterRequired ? nextMethod.MethodRequiredParameterInvocationWithCallback : nextMethod.MethodParameterInvocationWithCallback);
         builder.AppendLine(nextCall.Replace(
             string.Format(", {0}", nextMethod.ParameterModels.First(p => p.Name.StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name),
             "")).Outdent();
         builder.AppendLine("} else {").Indent();
         if (ReturnType.Headers == null)
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         else
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         builder.Outdent().AppendLine("}").Outdent().AppendLine("}");
         if (ReturnType.Headers == null)
         {
         builder.AppendLine("serviceCall.success(new {0}<>(result.getBody().getItems(), response));", ReturnTypeModel.ClientResponseType);
         }
         else
         {
             builder.AppendLine("serviceCall.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         return builder.ToString();
     }
     else if (this.IsPagingNextOperation)
     {
         var builder = new IndentedStringBuilder();
         builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeModel.WireResponseTypeString, this.Name);
         builder.AppendLine("serviceCallback.load(result.getBody().getItems());");
         builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent();
         builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent();
         var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.getBody().getNextPageLink(), {1});",
             this.Name,
             filterRequired ? MethodRequiredParameterInvocationWithCallback : MethodParameterInvocationWithCallback);
         builder.AppendLine(nextCall.Replace(
             string.Format(", {0}", ParameterModels.First(p => p.Name.StartsWith("next", StringComparison.OrdinalIgnoreCase)).Name),
             "")).Outdent();
         builder.AppendLine("} else {").Indent();
         if (ReturnType.Headers == null)
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         else
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         builder.Outdent().AppendLine("}");
         return builder.ToString();
     }
     else if (this.IsPagingNonPollingOperation)
     {
         var returnTypeBody = ReturnType.Body as AzureSequenceTypeModel;
         var builder = new IndentedStringBuilder();
         builder.AppendLine("{0}<{1}<{2}>> result = {3}Delegate(response);",
             ReturnTypeModel.ClientResponseType, returnTypeBody.PageImplType, returnTypeBody.ElementType.Name, this.Name.ToCamelCase());
         if (ReturnType.Headers == null)
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         else
         {
             builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType);
         }
         return builder.ToString();
     }
     return base.SuccessCallback();
 }
        /// <summary>
        /// Generates input mapping code block.
        /// </summary>
        /// <returns></returns>
        public virtual string BuildInputMappings(bool filterRequired = false)
        {
            var builder = new IndentedStringBuilder();
            foreach (var transformation in InputParameterTransformation)
            {
                var nullCheck = BuildNullCheckExpression(transformation);
                bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired && !filterRequired;
                if (conditionalAssignment)
                {
                    builder.AppendLine("{0} {1} = null;",
                            ((ParameterModel) transformation.OutputParameter).ClientType.ParameterVariant,
                            transformation.OutputParameter.Name);
                    builder.AppendLine("if ({0}) {{", nullCheck).Indent();
                }

                if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                    transformation.OutputParameter.Type is CompositeType)
                {
                    builder.AppendLine("{0}{1} = new {2}();",
                        !conditionalAssignment ? ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "",
                        transformation.OutputParameter.Name,
                        transformation.OutputParameter.Type.Name);
                }

                foreach (var mapping in transformation.ParameterMappings)
                {
                    builder.AppendLine("{0}{1}{2};",
                        !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ?
                            ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "",
                        transformation.OutputParameter.Name,
                        GetMapping(mapping, filterRequired));
                }

                if (conditionalAssignment)
                {
                    builder.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 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();
        }
Beispiel #18
0
        public virtual string BuildUrlPath(string variableName, IEnumerable<Parameter> pathParameters)
        {
            var builder = new IndentedStringBuilder("    ");
            if (pathParameters == null)
                return builder.ToString();

            var pathParameterList = pathParameters.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} = self._client.format_url({0}, **path_format_arguments)", variableName);
            }

            return builder.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();
        }
Beispiel #20
0
        public virtual string AddIndividualResponseHeader(HttpStatusCode? code)
        {
            IModelType headersType = null;

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

            var builder = new IndentedStringBuilder("    ");
            if (headersType == null)
            {
                if (code == null)
                {
                    builder.AppendLine("header_dict = {}");
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                builder.AppendLine("header_dict = {").Indent();
                AddHeaderDictionary(builder, (CompositeType)headersType);
                builder.Outdent().AppendLine("}");
            }
            return builder.ToString();
        }
Beispiel #21
0
        /// <summary>
        /// Generates input mapping code block.
        /// </summary>
        /// <returns></returns>
        public virtual string BuildInputMappings()
        {
            var builder = new IndentedStringBuilder("    ");
            foreach (var transformation in InputParameterTransformation)
            {
                if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
                    transformation.OutputParameter.ModelType is CompositeType)
                {
                    var comps = CodeModel.ModelTypes.Where(x => x.Name == transformation.OutputParameter.ModelTypeName);
                    var composite = comps.First();

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

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

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

            return builder.ToString();
        }
Beispiel #22
0
 private string convertClientTypeToWireType(ITypeModel wireType, string source, string target, string clientReference, int level = 0)
 {
     IndentedStringBuilder builder = new IndentedStringBuilder();
     if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123))
     {
         if (!IsRequired)
         {
             builder.AppendLine("DateTimeRfc1123 {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = new DateTimeRfc1123({2});", IsRequired ? "DateTimeRfc1123 " : "", target, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.UnixTime))
     {
         if (!IsRequired)
         {
             builder.AppendLine("Long {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = {2}.toDateTime(DateTimeZone.UTC).getMillis() / 1000;", IsRequired ? "Long " : "", target, source);
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.Base64Url))
     {
         if (!IsRequired)
         {
             builder.AppendLine("Base64Url {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = Base64Url.encode({2});", IsRequired ? "Base64Url " : "", target, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType.IsPrimaryType(KnownPrimaryType.Stream))
     {
         if (!IsRequired)
         {
             builder.AppendLine("RequestBody {0} = {1};", target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         builder.AppendLine("{0}{1} = RequestBody.create(MediaType.parse(\"{2}\"), {3});",
             IsRequired ? "RequestBody " : "", target, _method.RequestContentType, source);
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType is SequenceTypeModel)
     {
         if (!IsRequired)
         {
             builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         var sequenceType = wireType as SequenceTypeModel;
         var elementType = sequenceType.ElementTypeModel;
         var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         builder.AppendLine("{0}{1} = new ArrayList<{2}>();", IsRequired ? wireType.Name + " " : "", target, elementType.Name)
             .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source)
             .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1))
                 .AppendLine("{0}.add({1});", target, itemTarget)
             .Outdent().Append("}");
         _implImports.Add("java.util.ArrayList");
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     else if (wireType is DictionaryTypeModel)
     {
         if (!IsRequired)
         {
             builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method))
                 .AppendLine("if ({0} != null) {{", source).Indent();
         }
         var dictionaryType = wireType as DictionaryTypeModel;
         var valueType = dictionaryType.ValueTypeModel;
         var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture));
         builder.AppendLine("{0}{1} = new HashMap<String, {2}>();", IsRequired ? wireType.Name + " " : "", target, valueType.Name)
             .AppendLine("for (Map.Entry<String, {0}> {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source)
             .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1))
                 .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget)
             .Outdent().Append("}");
         _implImports.Add("java.util.HashMap");
         if (!IsRequired)
         {
             builder.Outdent().AppendLine("}");
         }
     }
     return builder.ToString();
 }