protected override void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false) { if (this.InputParameterTransformation.IsNullOrEmpty()) { return; } var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter; var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter; if (nextGroupType.Name == groupedType.Name) { return; } var nextGroupTypeName = _namer.GetTypeName(nextGroupType.Name) + "Inner"; if (filterRequired && !nextGroupType.IsRequired) { return; } if (!groupedType.IsRequired) { builder.AppendLine("{0} {1} = null;", nextGroupTypeName, nextGroupType.Name.ToCamelCase()); builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase()); builder.Indent(); builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName); } else { builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName); } foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter)) { builder.AppendLine("{0}.with{1}({2}.{3}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase(), outParam.Name.ToCamelCase()); } if (!groupedType.IsRequired) { builder.Outdent().AppendLine(@"}"); } }
/// <summary> /// Generate code to perform deserialization on a parameter or property /// </summary> /// <param name="type">The type to deserialize</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="objectReference">A reference to the object that will be assigned the deserialized value</param> /// <param name="valueReference">A reference to the value being deserialized</param> /// <param name="modelReference">A reference to the models</param> /// <returns>The code to deserialize the given type</returns> public static string DeserializeType(this IType type, IScopeProvider scope, string objectReference, string valueReference, string modelReference = "self._models") { if (scope == null) { throw new ArgumentNullException("scope"); } EnumType enumType = type as EnumType; CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); string baseProperty = valueReference.GetBasePropertyFromUnflattenedProperty(); if (baseProperty != null) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", baseProperty).Indent(); } if (enumType != null) { builder = ProcessBasicType(objectReference, valueReference, builder); } else if (primary != null) { if (primary == PrimaryType.ByteArray) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = new Buffer({0}, 'base64');", valueReference, objectReference) .Outdent().AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date || primary == PrimaryType.DateTimeRfc1123) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = new Date({0});", valueReference, objectReference) .Outdent() .AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else if (primary == PrimaryType.TimeSpan) { builder.AppendLine("if ({0}) {{", valueReference) .Indent() .AppendLine("{1} = moment.duration({0});", valueReference, objectReference) .Outdent() .AppendLine("}") .AppendLine("else if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("if ({0} !== undefined) {{", valueReference) .Indent() .AppendLine("{1} = {0};", valueReference, objectReference) .Outdent() .AppendLine("}"); } } else if (composite != null && composite.Properties.Any()) { builder = composite.ProcessCompositeType(objectReference, valueReference, modelReference, builder, "DeserializeType"); } else if (sequence != null) { builder = sequence.ProcessSequenceType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType"); } else if (dictionary != null) { builder = dictionary.ProcessDictionaryType(scope, objectReference, valueReference, modelReference, builder, "DeserializeType"); } if (baseProperty != null) { builder.Outdent().AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generate code to build the URL from a url expression and method parameters /// </summary> /// <param name="variableName">The variable to store the url in.</param> /// <returns></returns> public virtual string BuildUrl(string variableName) { var builder = new IndentedStringBuilder(); foreach (var pathParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Path)) { string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", Uri.EscapeDataString({2}));"; if (pathParameter.SkipUrlEncoding()) { replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } builder.AppendLine(replaceString, variableName, pathParameter.SerializedName, pathParameter.Type.ToString(ClientReference, pathParameter.Name)); } if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query)) { builder.AppendLine("List<string> _queryParameters = new List<string>();"); foreach (var queryParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Query)) { var replaceString = "_queryParameters.Add(string.Format(\"{0}={{0}}\", 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}));"; } 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(); }
public virtual string AddIndividualResponseHeader(HttpStatusCode? code) { IType headersType = null; if (HasResponseHeader) { if (code != null) { headersType = this.ReturnType.Headers; } else { headersType = this.Responses[code.Value].Headers; } } var builder = new IndentedStringBuilder(" "); if (headersType == null) { if (code == null) { builder.AppendLine("header_dict = {}"); } else { return string.Empty; } } else { builder.AppendLine("header_dict = {").Indent(); AddHeaderDictionary(builder, (CompositeType)headersType); builder.Outdent().AppendLine("}"); } return builder.ToString(); }
public string DeserializeResponse(IType type, string valueReference = "result", string responseVariable = "parsedResponse") { if (type == null) { throw new ArgumentNullException("type"); } var builder = new IndentedStringBuilder(" "); builder.AppendLine("var {0} = null;", responseVariable) .AppendLine("try {") .Indent() .AppendLine("{0} = JSON.parse(responseBody);", responseVariable) .AppendLine("{0} = JSON.parse(responseBody);", valueReference); var deserializeBody = GetDeserializationString(type, valueReference, responseVariable); if (!string.IsNullOrWhiteSpace(deserializeBody)) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable) .Indent() .AppendLine(deserializeBody) .Outdent() .AppendLine("}"); } builder.Outdent() .AppendLine("} catch (error) {") .Indent() .AppendLine(DeserializationError) .Outdent() .AppendLine("}"); return builder.ToString(); }
public virtual string BuildFlattenParameterMappings() { var builder = new IndentedStringBuilder(); foreach (var transformation in InputParameterTransformation) { builder.AppendLine("var {0};", transformation.OutputParameter.Name); builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation)) .AppendLine("{").Indent(); if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0} = new client.models['{1}']();", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1};", transformation.OutputParameter.Name, mapping); } builder.Outdent() .AppendLine("}"); } return builder.ToString(); }
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(); }
private static string SerializeCompositeType(this CompositeType composite, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, string modelReference = "client._models", bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedObjectReference = objectReference.EscapeSingleQuotes(); builder.AppendLine("if ({0}) {{", objectReference).Indent(); builder = composite.AppendConstraintValidations(objectReference, constraints, builder); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", objectReference, composite.PolymorphicDiscriminator, modelReference) .Indent(); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, escapedObjectReference) .Outdent() .AppendLine("}"); } else { if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1}.serialize();", valueReference, objectReference); } builder.Outdent().AppendLine("}"); if (isRequired) { builder.Append(" else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedObjectReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generate code to perform validation on a parameter or property /// </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="modelReference">A reference to the models array</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference, string modelReference = "client._models") { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); if(primary != null) { if (primary == PrimaryType.String || primary == PrimaryType.Boolean || primary == PrimaryType.Double || primary == PrimaryType.Int || primary == PrimaryType.Long) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, primary.Name.ToLower(CultureInfo.InvariantCulture)) .Indent() .AppendLine("throw new Error('{0} must be of type {1}.');", escapedValueReference, primary.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.ByteArray) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && !Buffer.isBuffer({0})) {{", valueReference) .Indent() .AppendLine("throw new Error('{0} must be of type {1}.');", escapedValueReference, primary.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && ", valueReference) .Indent() .Indent() .AppendLine("!({0} instanceof Date || ", valueReference) .Indent() .AppendLine("(typeof {0} === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference) .Outdent() .Outdent() .AppendLine("throw new Error('{0} must be of type {1}.');", escapedValueReference, primary.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.Object) { return builder.ToString(); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } } else if (enumType != null && enumType.Values.Any()) { var allowedValues = scope.GetVariableName("allowedValues"); return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", 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("}") .Outdent() .AppendLine("}").ToString(); } else if (composite != null && composite.Properties.Any()) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference).Indent(); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator, modelReference) .Indent() .AppendLine("{2}.discriminators[{0}['{1}']].validate({0});", valueReference, composite.PolymorphicDiscriminator, modelReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, escapedValueReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{2}['{0}'].validate({1});", composite.Name, valueReference, modelReference); } builder.Outdent().AppendLine("}"); return builder.ToString(); } else if (sequence != null) { var indexVar = scope.GetVariableName("i"); var innerValidation = sequence.ElementType.ValidateType(scope, valueReference + "["+indexVar+"]", modelReference); if (!string.IsNullOrEmpty(innerValidation)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && util.isArray({0})) {{", valueReference) .Indent() .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueReference + "[" + valueVar + "]", modelReference); if (!string.IsNullOrEmpty(innerValidation)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} === 'object') {{", valueReference) .Indent() .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } } return null; }
/// <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) { if (filterRequired && !mapping.InputParameter.IsRequired) { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? ((ParameterModel)transformation.OutputParameter).WireType + " " : "", ((ParameterModel)transformation.OutputParameter).WireName, " = " + ((ParameterModel)transformation.OutputParameter).WireType.DefaultValue(this)); } else { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", transformation.OutputParameter.Name, GetMapping(mapping)); } } if (conditionalAssignment) { builder.Outdent() .AppendLine("}"); } } return builder.ToString(); }
public string GetDeserializationString(IType type, string valueReference = "result", string responseVariable = "parsedResponse") { CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.DateTime || primary == PrimaryType.Date || primary == PrimaryType.DateTimeRfc1123) { builder.AppendLine("{0} = new Date({0});", valueReference); } else if (primary == PrimaryType.ByteArray) { builder.AppendLine("{0} = new Buffer({0}, 'base64');", valueReference); } else if (primary == PrimaryType.TimeSpan) { builder.AppendLine("{0} = moment.duration({0});", valueReference); } } else if (IsSpecialProcessingRequired(sequence)) { builder.AppendLine("for (var i = 0; i < {0}.length; i++) {{", valueReference) .Indent(); // Loop through the sequence if each property is Date, DateTime or ByteArray // as they need special treatment for deserialization if (sequence.ElementType is PrimaryType) { builder.AppendLine("if ({0}[i] !== null && {0}[i] !== undefined) {{", valueReference) .Indent(); if (sequence.ElementType == PrimaryType.DateTime || sequence.ElementType == PrimaryType.Date || sequence.ElementType == PrimaryType.DateTimeRfc1123) { builder.AppendLine("{0}[i] = new Date({0}[i]);", valueReference); } else if (sequence.ElementType == PrimaryType.ByteArray) { builder.AppendLine("{0}[i] = new Buffer({0}[i], 'base64');", valueReference); } else if (sequence.ElementType == PrimaryType.TimeSpan) { builder.AppendLine("{0}[i] = moment.duration({0}[i]);", valueReference); } } else if (sequence.ElementType is CompositeType) { builder.AppendLine("if ({0}[i] !== null && {0}[i] !== undefined) {{", valueReference) .Indent() .AppendLine(GetDeserializationString(sequence.ElementType, string.Format(CultureInfo.InvariantCulture, "{0}[i]", valueReference), string.Format(CultureInfo.InvariantCulture, "{0}[i]", responseVariable))); } builder.Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); } else if (IsSpecialProcessingRequired(dictionary)) { builder.AppendLine("for (var property in {0}) {{", valueReference) .Indent(); if (dictionary.ValueType is PrimaryType) { builder.AppendLine("if ({0}[property] !== null && {0}[property] !== undefined) {{", valueReference) .Indent(); if (dictionary.ValueType == PrimaryType.DateTime || dictionary.ValueType == PrimaryType.Date || dictionary.ValueType == PrimaryType.DateTimeRfc1123) { builder.AppendLine("{0}[property] = new Date({0}[property]);", valueReference); } else if (dictionary.ValueType == PrimaryType.ByteArray) { builder.AppendLine("{0}[property] = new Buffer({0}[property], 'base64');", valueReference); } else if (dictionary.ValueType == PrimaryType.TimeSpan) { builder.AppendLine("{0}[property] = moment.duration({0}[property]);", valueReference); } } else if (dictionary.ValueType is CompositeType) { builder.AppendLine("if ({0}[property] !== null && {0}[property] !== undefined) {{", valueReference) .Indent() .AppendLine(GetDeserializationString(dictionary.ValueType, string.Format(CultureInfo.InvariantCulture, "{0}[property]", valueReference), string.Format(CultureInfo.InvariantCulture, "{0}[property]", responseVariable))); } builder.Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); } else if (composite != null) { builder.AppendLine("{0}.deserialize({1});", valueReference, responseVariable); } else if (enumType != null) { //Do No special deserialization } else { return string.Empty; } return builder.ToString(); }
private void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod) { if (this.InputParameterTransformation.IsNullOrEmpty()) { return; } var groupedType = this.InputParameterTransformation.FirstOrDefault().ParameterMappings[0].InputParameter; var nextGroupType = nextMethod.InputParameterTransformation.FirstOrDefault().ParameterMappings[0].InputParameter; if (nextGroupType.Name == groupedType.Name) { return; } if (!groupedType.IsRequired) { builder.AppendLine("{0} {1} = null;", nextGroupType.Name.ToPascalCase(), nextGroupType.Name.ToCamelCase()); builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase()); builder.Indent(); builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupType.Name.ToPascalCase()); } else { builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupType.Name.ToPascalCase()); } foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter)) { builder.AppendLine("{0}.set{1}({2}.get{1}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase()); } if (!groupedType.IsRequired) { builder.Outdent().AppendLine(@"}"); } }
/// <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(); }
private static IndentedStringBuilder ProcessCompositeType(this CompositeType composite, string objectReference, string valueReference, string modelReference, IndentedStringBuilder builder, string processType) { builder.AppendLine("if ({0}) {{", valueReference).Indent(); string discriminator = "{3} = new {2}.discriminators[{0}['{1}']]({0});"; string objectCreation = "{3} = new {2}['{1}']({0});"; if (processType == "DeserializeType") { discriminator = "{3} = new {2}.discriminators[{0}['{1}']]().deserialize({0});"; objectCreation = "{3} = new {2}['{1}']().deserialize({0});"; } if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine(discriminator, valueReference, composite.PolymorphicDiscriminator, modelReference, objectReference); } else { builder.AppendLine(objectCreation, valueReference, composite.Name, modelReference, objectReference); } builder.Outdent().AppendLine("}"); return builder; }
private static string ValidateCompositeType(this CompositeType composite, 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(); builder.AppendLine("if ({0}) {{", valueReference).Indent(); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator, modelReference) .Indent() .AppendLine("{2}.discriminators[{0}['{1}']].validate({0});", valueReference, composite.PolymorphicDiscriminator, modelReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, escapedValueReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{2}['{0}'].validate({1});", composite.Name, valueReference, modelReference); } builder.Outdent().AppendLine("}"); if (isRequired) { builder.Append(" else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
private static string SerializeEnumType(this EnumType enumType, IScopeProvider scope, string objectReference, string valueReference, bool isRequired, Dictionary<Constraint, string> constraints, bool serializeInnerTypes = false) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var allowedValues = scope.GetVariableName("allowedValues"); string tempReference = objectReference; builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", objectReference).Indent(); builder = enumType.AppendConstraintValidations(objectReference, constraints, builder); builder.AppendLine("var {0} = {1};", allowedValues, enumType.GetEnumValuesArray()); if (objectReference.IndexOfAny(new char[] { '.', '[', ']'}) >= 0) { tempReference = tempReference.NormalizeValueReference(); builder.AppendLine("var {0} = {1};", tempReference, objectReference); } builder.AppendLine("if (!{0}.some( function(item) {{ return item === {1}; }})) {{", allowedValues, tempReference) .Indent() .AppendLine("throw new Error({0} + ' is not a valid value. The valid values are: ' + {1});", objectReference, allowedValues) .Outdent() .AppendLine("}"); if (!serializeInnerTypes) builder = ConstructBasePropertyCheck(builder, valueReference); builder.AppendLine("{0} = {1};", valueReference, objectReference); if (isRequired) { var escapedObjectReference = objectReference.EscapeSingleQuotes(); builder.Outdent().AppendLine("} else {") .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedObjectReference) .Outdent() .AppendLine("}"); } else { builder.Outdent().AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generate code to perform deserialization on a parameter or property /// </summary> /// <param name="type">The type to deserialize</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being deserialized</param> /// <param name="modelReference">A reference to the models</param> /// <returns>The code to deserialize the given type</returns> public static string DeserializeType(this IType type, IScopeProvider scope, string valueReference, string modelReference = "self._models") { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.ByteArray) { return builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() === 'string') {{", valueReference) .Indent() .AppendLine("{0} = new Buffer({0}, 'base64');", valueReference) .Outdent() .AppendLine("}").ToString(); } else if (primary == PrimaryType.DateTime || primary == PrimaryType.Date) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("{0} = new Date({0});", valueReference) .Outdent() .AppendLine("}").ToString(); } } else if (composite != null && composite.Properties.Any()) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference).Indent(); if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && {2}.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator, modelReference) .Indent() .AppendLine("{0} = {2}.discriminators[{0}['{1}']].deserialize({0});", valueReference, composite.PolymorphicDiscriminator, modelReference) .Outdent() .AppendLine("}} else {{", valueReference) .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in parameter \"{1}\".');", composite.PolymorphicDiscriminator, valueReference) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{0} = {2}['{1}'].deserialize({0});", valueReference, composite.Name, modelReference); } builder.Outdent().AppendLine("}"); return builder.ToString(); } else if (sequence != null) { var elementVar = scope.GetVariableName("element"); var innerSerialization = sequence.ElementType.DeserializeType(scope, elementVar, modelReference); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("var deserialized{0} = [];", sequence.Name.ToPascalCase()) .AppendLine("{0}.forEach(function({1}) {{", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized{0}.push({1});", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("});") .AppendLine("{0} = deserialized{1};", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("}").ToString(); } } else if (dictionary != null) { var valueVar = scope.GetVariableName("valueElement"); var innerSerialization = dictionary.ValueType.DeserializeType(scope, valueReference + "[" + valueVar + "]", modelReference); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", valueReference) .Indent() .AppendLine("for(var {0} in {1}) {{", valueVar, valueReference) .Indent() .AppendLine(innerSerialization) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } } return null; }
/// <summary> /// Generate code to construct the query string from an array of query parameter strings containing 'key=value' /// </summary> /// <param name="variableName">The variable reference for the url</param> /// <param name="builder">The string builder for url construction</param> private 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 string AssignDefaultValues() { IEnumerable<Property> optionalParamsWithDefaultsList = Properties.Where(p => !p.IsRequired && !string.IsNullOrWhiteSpace(p.DefaultValue)); var builder = new IndentedStringBuilder(" "); if (optionalParamsWithDefaultsList.Count() > 0) { builder.AppendLine("if (parameters === null || parameters === undefined) {") .Indent() .AppendLine("parameters = {};") .Outdent() .AppendLine("}"); foreach (var optionalParamWithDefault in optionalParamsWithDefaultsList) { builder.AppendLine("if (parameters.{0} === undefined) {{", optionalParamWithDefault.Name).Indent(); if (optionalParamWithDefault.Type == PrimaryType.String || optionalParamWithDefault.Type is EnumType) { builder.AppendLine("parameters.{0} = '{1}';", optionalParamWithDefault.Name, optionalParamWithDefault.DefaultValue); } else { builder.AppendLine("parameters.{0} = {1};", optionalParamWithDefault.Name, optionalParamWithDefault.DefaultValue); } 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) { 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.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(); }
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("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 = GetPagingNextMethod(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(", nextPageLink", "")).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.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(", nextPageLink", "")).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 builder = new IndentedStringBuilder(); builder.AppendLine("{0}<{3}<{1}>> result = {2}Delegate(response);", ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase(), pageClassName); 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(); }
public virtual string BuildGroupedParameterMappings() { var builder = new IndentedStringBuilder(" "); if (InputParameterTransformation.Count > 0) { // Declare all the output paramaters outside the try block foreach (var transformation in InputParameterTransformation) { builder.AppendLine("var {0};", transformation.OutputParameter.Name); } builder.AppendLine("try {").Indent(); foreach (var transformation in InputParameterTransformation) { builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation)) .AppendLine("{").Indent(); var outputParameter = transformation.OutputParameter; bool noCompositeTypeInitialized = true; if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0} = new client.models['{1}']();", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); noCompositeTypeInitialized = false; } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1};", transformation.OutputParameter.Name, mapping); if (noCompositeTypeInitialized) { // If composite type is initialized based on the above logic then it shouuld not be validated. builder.AppendLine(outputParameter.Type.ValidateType(Scope, outputParameter.Name, outputParameter.IsRequired)); } } builder.Outdent() .AppendLine("}"); } builder.Outdent() .AppendLine("} catch (error) {") .Indent() .AppendLine("return callback(error);") .Outdent() .AppendLine("}"); } return builder.ToString(); }
/// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(" "); foreach (var transformation in InputParameterTransformation) { if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { var comps = ServiceClient.ModelTypes.Where(x => x.Name == transformation.OutputParameter.Type.Name); 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 == 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.Type.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(); }
public virtual string BuildUrlPath(string variableName) { var builder = new IndentedStringBuilder(" "); var pathParameterList = this.LogicalParameters.Where(p => p.Location == ParameterLocation.Path).ToList(); if (pathParameterList.Any()) { builder.AppendLine("path_format_arguments = {").Indent(); for (int i = 0; i < pathParameterList.Count; i ++) { builder.AppendLine("'{0}': {1}{2}{3}", pathParameterList[i].SerializedName, BuildSerializeDataCall(pathParameterList[i], "url"), pathParameterList[i].IsRequired ? string.Empty : string.Format(CultureInfo.InvariantCulture, "if {0} else ''", pathParameterList[i].Name), i == pathParameterList.Count-1 ? "" : ","); } builder.Outdent().AppendLine("}"); builder.AppendLine("{0} = {0}.format(**path_format_arguments)", variableName); } return builder.ToString(); }
public string GetDeserializationString(IType type, string valueReference = "result.body") { CompositeType composite = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary == PrimaryType.DateTime || primary == PrimaryType.Date) { builder.AppendLine("{0} = new Date({0});", valueReference); } else if (primary == PrimaryType.ByteArray) { builder.AppendLine("{0} = new Buffer({0}, 'base64');", valueReference); } } else if (IsSpecialDeserializationRequired(sequence)) { builder.AppendLine("for (var i = 0; i < {0}.length; i++) {{", valueReference) .Indent() .AppendLine("if ({0}[i] !== null && {0}[i] !== undefined) {{", valueReference) .Indent(); // Loop through the sequence if each property is Date, DateTime or ByteArray // as they need special treatment for deserialization if (sequence.ElementType == PrimaryType.DateTime || sequence.ElementType == PrimaryType.Date) { builder.AppendLine("{0}[i] = new Date({0}[i]);", valueReference); } else if (sequence.ElementType == PrimaryType.ByteArray) { builder.AppendLine("{0}[i] = new Buffer({0}[i], 'base64');", valueReference); } else if (sequence.ElementType is CompositeType) { builder.AppendLine(GetDeserializationString(sequence.ElementType, string.Format(CultureInfo.InvariantCulture, "{0}[i]", valueReference))); } builder.Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); } else if (IsSpecialDeserializationRequired(dictionary)) { builder.AppendLine("for (var property in {0}) {{", valueReference) .Indent() .AppendLine("if ({0}[property] !== null && {0}[property] !== undefined) {{", valueReference) .Indent(); if (dictionary.ValueType == PrimaryType.DateTime || dictionary.ValueType == PrimaryType.Date) { builder.AppendLine("{0}[property] = new Date({0}[property]);", valueReference); } else if (dictionary.ValueType == PrimaryType.ByteArray) { builder.AppendLine("{0}[property] = new Buffer({0}[property], 'base64');", valueReference); } else if (dictionary.ValueType is CompositeType) { builder.AppendLine(GetDeserializationString(dictionary.ValueType, string.Format(CultureInfo.InvariantCulture, "{0}[property]", valueReference))); } builder.Outdent() .AppendLine("}") .Outdent() .AppendLine("}"); } else if (composite != null) { if (!string.IsNullOrEmpty(composite.PolymorphicDiscriminator)) { builder.AppendLine("if({0}['{1}'] !== null && {0}['{1}'] !== undefined && client._models.discriminators[{0}['{1}']]) {{", valueReference, composite.PolymorphicDiscriminator) .Indent() .AppendLine("{0} = client._models.discriminators[{0}['{1}']].deserialize({0});", valueReference, composite.PolymorphicDiscriminator) .Outdent() .AppendLine("} else {") .Indent() .AppendLine("throw new Error('No discriminator field \"{0}\" was found in response.');", composite.PolymorphicDiscriminator) .Outdent() .AppendLine("}"); } else { builder.AppendLine("{0} = client._models['{1}'].deserialize({0});", valueReference, type.Name); } } else if (enumType != null) { //Do No special deserialization } else { return string.Empty; } return builder.ToString(); }
/// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(" "); foreach (var transformation in InputParameterTransformation) { if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0} = models.{1}()", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } else { builder.AppendLine("{0} = None", transformation.OutputParameter.Name); } builder.AppendLine("if {0}:", BuildNullCheckExpression(transformation)) .Indent(); foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1}", transformation.OutputParameter.Name, mapping); } builder.Outdent(); } return builder.ToString(); }
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.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(); }