public override string ConstructModelMapper() { var modelMapper = this.ConstructMapper(SerializedName, null, true, true); var builder = new IndentedStringBuilder(" "); builder.AppendLine("return {{{0}}};", modelMapper); return builder.ToString(); }
public string GetOperationsRequiredFiles() { var sb = new IndentedStringBuilder(); this.MethodGroups.ForEach(method => sb.AppendLine("{0}", this.GetRequiredFormat(RubyCodeNamer.UnderscoreCase(method) + ".rb"))); return sb.ToString(); }
/// <summary> /// Generates code for model serialization. /// </summary> /// <param name="variableName">Variable serialize model from.</param> /// <param name="type">The type of the model.</param> /// <returns>The code for serialization in string format.</returns> public override string SerializeProperty(string variableName, IType type) { var builder = new IndentedStringBuilder(" "); string serializationLogic = type.AzureSerializeType(this.Scope, variableName); builder.AppendLine(serializationLogic); return builder.ToString(); }
public string GetModelsRequiredFiles() { var sb = new IndentedStringBuilder(); this.GetOrderedModels().Where(m => !m.Extensions.ContainsKey(ExternalExtension)).ForEach(model => sb.AppendLine("{0}", this.GetRequiredFormat("models/" + RubyCodeNamer.UnderscoreCase(model.Name) + ".rb"))); this.EnumTypes.ForEach(enumType => sb.AppendLine(this.GetRequiredFormat("models/" + RubyCodeNamer.UnderscoreCase(enumType.Name) + ".rb"))); return sb.ToString(); }
/// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(" "); if (InputParameterTransformation.Count > 0) { if (AreWeFlatteningParameters()) { return BuildFlattenParameterMappings(); } else { return BuildGroupedParameterMappings(); } } return builder.ToString(); }
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(); }
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(); }
/// <summary> /// Generate code to build the headers from method parameters /// </summary> /// <param name="variableName">The variable to store the headers in.</param> /// <returns></returns> public virtual string BuildHeaders(string variableName) { var builder = new IndentedStringBuilder(" "); foreach (var headerParameter in this.LogicalParameters.Where(p => p.Location == ParameterLocation.Header)) { if (headerParameter.IsRequired) { builder.AppendLine("{0}['{1}'] = {2}", variableName, headerParameter.SerializedName, BuildSerializeDataCall(headerParameter, "header")); } else { builder.AppendLine("if {0} is not None:", headerParameter.Name) .Indent() .AppendLine("{0}['{1}'] = {2}", variableName, headerParameter.SerializedName, BuildSerializeDataCall(headerParameter, "header")) .Outdent(); } } return builder.ToString(); }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference) { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType model = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; if (model != null && model.ShouldValidateChain()) { return CheckNull(valueReference, string.Format(CultureInfo.InvariantCulture, "{0}.Validate();", valueReference)); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetVariableName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar); if (!string.IsNullOrEmpty(innerValidation)) { var sb = new IndentedStringBuilder(); sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); return CheckNull(valueReference, sb.ToString()); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetVariableName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar); if (!string.IsNullOrEmpty(innerValidation)) { var sb = new IndentedStringBuilder(); sb.AppendLine("if ({0} != null)", valueReference) .AppendLine("{").Indent() .AppendLine("foreach (var {0} in {1}.Values)",valueVar,valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent() .AppendLine("}"); return CheckNull(valueReference, sb.ToString()); } } return null; }
/// <summary> /// Generate code to remove duplicated forward slashes from a URL in code /// </summary> /// <param name="urlVariableName"></param> /// <returns></returns> public virtual string RemoveDuplicateForwardSlashes(string urlVariableName) { var builder = new IndentedStringBuilder(" "); builder.AppendLine("// trim all duplicate forward slashes in the url"); builder.AppendLine("var regex = /([^:]\\/)\\/+/gi;"); builder.AppendLine("{0} = {0}.replace(regex, '$1');", urlVariableName); return builder.ToString(); }
public string DeserializeResponse(IType type, string valueReference = "result", string responseVariable = "parsedResponse") { if (type == null) { throw new ArgumentNullException("type"); } var builder = new IndentedStringBuilder(" "); builder.AppendLine("var {0} = null;", responseVariable) .AppendLine("try {") .Indent() .AppendLine("{0} = JSON.parse(responseBody);", responseVariable) .AppendLine("{0} = JSON.parse(responseBody);", valueReference); var deserializeBody = GetDeserializationString(type, valueReference, responseVariable); if (!string.IsNullOrWhiteSpace(deserializeBody)) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable) .Indent() .AppendLine(deserializeBody) .Outdent() .AppendLine("}"); } builder.Outdent() .AppendLine("} catch (error) {") .Indent() .AppendLine(DeserializationError) .Outdent() .AppendLine("}"); return builder.ToString(); }
public string BuildOptionalMappings() { IEnumerable<Property> optionalParameters = ((CompositeType)OptionsParameterTemplateModel.Type) .Properties.Where(p => p.Name != "customHeaders"); var builder = new IndentedStringBuilder(" "); foreach (var optionalParam in optionalParameters) { string defaultValue = "undefined"; if (!string.IsNullOrWhiteSpace(optionalParam.DefaultValue)) { defaultValue = optionalParam.DefaultValue; } builder.AppendLine("var {0} = ({1} && {1}.{2} !== undefined) ? {1}.{2} : {3};", optionalParam.Name, OptionsParameterTemplateModel.Name, optionalParam.Name, defaultValue); } return builder.ToString(); }
/// <summary> /// Returns the list of model files for 'autoloading' them. /// </summary> /// <returns>Model files list in form of string.</returns> public string GetModelsRequiredFiles() { var sb = new IndentedStringBuilder(); this.GetOrderedModels() .Where(m => !ExcludeModel(m)) .ForEach(model => sb.AppendLine(this.GetAutoloadFormat(model.Name, "models/" + RubyCodeNamer.UnderscoreCase(model.Name) + this.implementationFileExtension))); this.EnumTypes.ForEach(enumType => sb.AppendLine(this.GetAutoloadFormat(enumType.Name, "models/" + RubyCodeNamer.UnderscoreCase(enumType.Name) + this.implementationFileExtension))); return sb.ToString(); }
/// <summary> /// Returns a list of methods groups for 'autoloading' them. /// </summary> /// <returns>Method groups list in form of string.</returns> public string GetOperationsRequiredFiles() { var sb = new IndentedStringBuilder(); this.MethodGroups.ForEach(method => sb.AppendLine("{0}", this.GetAutoloadFormat(method, RubyCodeNamer.UnderscoreCase(method) + this.implementationFileExtension))); return sb.ToString(); }
/// <summary> /// Creates deserialization logic for the given <paramref name="type"/>. /// </summary> /// <param name="type">Type for which deserialization logic being constructed.</param> /// <param name="valueReference">Reference variable name.</param> /// <param name="responseVariable">Response variable name.</param> /// <returns>Deserialization logic for the given <paramref name="type"/> as string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public string GetDeserializationString(IType type, string valueReference = "result", string responseVariable = "parsed_response") { if (type == null) { throw new ArgumentNullException(nameof(type)); } var builder = new IndentedStringBuilder(" "); if (type is CompositeType) { builder.AppendLine("result_mapper = {0}.mapper()", type.Name); } else { builder.AppendLine("result_mapper = {{{0}}}", type.ConstructMapper(responseVariable, null, false)); } if (Group == null) { builder.AppendLine("{1} = self.deserialize(result_mapper, {0}, '{1}')", responseVariable, valueReference); } else { builder.AppendLine("{1} = @client.deserialize(result_mapper, {0}, '{1}')", responseVariable, valueReference); } return builder.ToString(); }
/// <summary> /// Constructs mapper for the request body. /// </summary> /// <param name="outputVariable">Name of the output variable.</param> /// <returns>Mapper for the request body as string.</returns> public string ConstructRequestBodyMapper(string outputVariable = "request_mapper") { var builder = new IndentedStringBuilder(" "); if (RequestBody.Type is CompositeType) { builder.AppendLine("{0} = {1}.mapper()", outputVariable, RequestBody.Type.Name); } else { builder.AppendLine("{0} = {{{1}}}", outputVariable, RequestBody.Type.ConstructMapper(RequestBody.SerializedName, RequestBody, false)); } 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(" "); BuildPathParameters(variableName, builder); return builder.ToString(); }
/// <summary> /// Ensures that there is no duplicate forward slashes in the url. /// </summary> /// <param name="urlVariableName">The url variable.</param> /// <returns>Updated url.</returns> public virtual string RemoveDuplicateForwardSlashes(string urlVariableName) { var builder = new IndentedStringBuilder(" "); // Removing duplicate forward slashes. builder.AppendLine(@"corrected_url = {0}.to_s.gsub(/([^:])\/\//, '\1/')", urlVariableName); builder.AppendLine(@"{0} = URI.parse(corrected_url)", urlVariableName); 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(" "); BuildPathParameters(variableName, builder); if (HasQueryParameters()) { BuildQueryParameterArray(builder); AddQueryParametersToUrl(variableName, builder); } 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(); }
public string GetDeserializationString(IType type, string valueReference = "result", string responseVariable = "parsedResponse") { var builder = new IndentedStringBuilder(" "); if (type is CompositeType) { builder.AppendLine("var resultMapper = new client.models['{0}']().mapper();", type.Name); } else { builder.AppendLine("var resultMapper = {{{0}}};", type.ConstructMapper(responseVariable, null, false, false)); } builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference); return builder.ToString(); }
private static string ValidateCompositeType(IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); //Only validate whether the composite type is present, if it is required. Detailed validation happens in serialization. if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined.');", escapedValueReference) .Outdent() .AppendLine("}"); } return builder.ToString(); }
public static string CheckNull(string valueReference, string executionBlock) { var sb = new IndentedStringBuilder(); sb.AppendLine("if ({0} != null)", valueReference) .AppendLine("{").Indent() .AppendLine(executionBlock).Outdent() .AppendLine("}"); return sb.ToString(); }
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 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(); }
/// <summary> /// Generate code to build the URL from a url expression and method parameters /// </summary> /// <param name="variableName">The variable to store the url in.</param> /// <returns></returns> public virtual string BuildUrl(string variableName) { var builder = new IndentedStringBuilder(); foreach (var pathParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Path)) { builder.AppendLine("{0} = {0}.Replace(\"{{{1}}}\", Uri.EscapeDataString({2}));", variableName, pathParameter.SerializedName, pathParameter.Type.ToString(ClientReference, pathParameter.Name)); } if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query)) { builder.AppendLine("List<string> _queryParameters = new List<string>();"); foreach (var queryParameter in this.LogicalParameterTemplateModels.Where(p => p.Location == ParameterLocation.Query)) { builder.AppendLine("if ({0} != null)", queryParameter.Name) .AppendLine("{").Indent() .AppendLine("_queryParameters.Add(string.Format(\"{0}={{0}}\", Uri.EscapeDataString({1})));", queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue(ClientReference)).Outdent() .AppendLine("}"); } builder.AppendLine("if (_queryParameters.Count > 0)") .AppendLine("{").Indent() .AppendLine("{0} += \"?\" + string.Join(\"&\", _queryParameters);", variableName).Outdent() .AppendLine("}"); } return builder.ToString(); }
public virtual string AddResponseHeader() { if (HasResponseHeader) { var builder = new IndentedStringBuilder(" "); builder.AppendLine("client_raw_response.add_headers(header_dict)"); return builder.ToString(); } else { return string.Empty; } }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <param name="constraints">Constraints</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IType type, IScopeProvider scope, string valueReference, Dictionary<Constraint, string> constraints) { if (scope == null) { throw new ArgumentNullException("scope"); } CompositeType model = type as CompositeType; SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; var sb = new IndentedStringBuilder(); if (model != null && model.ShouldValidateChain()) { sb.AppendLine("{0}.Validate();", valueReference); } if (constraints != null && constraints.Any()) { AppendConstraintValidations(valueReference, constraints, sb); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetUniqueName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetUniqueName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent(); } } if (sb.ToString().Trim().Length > 0) { if (type.IsValueType()) { return sb.ToString(); } else { return CheckNull(valueReference, sb.ToString()); } } return null; }
/// <summary> /// Generates input mapping code block. /// </summary> /// <returns></returns> public virtual string BuildInputMappings() { var builder = new IndentedStringBuilder(" "); foreach (var transformation in InputParameterTransformation) { if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0} = models.{1}()", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } else { builder.AppendLine("{0} = None", transformation.OutputParameter.Name); } builder.AppendLine("if {0}:", BuildNullCheckExpression(transformation)) .Indent(); foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1}", transformation.OutputParameter.Name, mapping); } builder.Outdent(); } return builder.ToString(); }
public 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(); }