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 void AppendDoesNotAddIndentation(string input) { IndentedStringBuilder sb = new IndentedStringBuilder(); var expected = input; var result = sb.Indent().Append(input); Assert.Equal(expected, result.ToString()); }
public void AppendWorksWithNull() { IndentedStringBuilder sb = new IndentedStringBuilder(); var expected = ""; var result = sb.Indent().Append(null); Assert.Equal(expected, result.ToString()); }
/// <summary> /// Generates Ruby code in form of string for deserializing polling response. /// </summary> /// <param name="variableName">Variable name which keeps the response.</param> /// <param name="type">Type of response.</param> /// <returns>Ruby code in form of string for deserializing polling response.</returns> public string DeserializePollingResponse(string variableName, IModelType type) { var builder = new IndentedStringBuilder(" "); string serializationLogic = GetDeserializationString(type, variableName, variableName); return(builder.AppendLine(serializationLogic).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 override string BuildUrl(string variableName) { var builder = new IndentedStringBuilder(IndentedStringBuilder.FourSpaces); ReplacePathParametersInUri(variableName, builder); AddQueryParametersToUri(variableName, builder); 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(); }
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("}"); }
public string GetLongRunningOperationResponse(string clientReference) { var builder = new IndentedStringBuilder(" "); string lroOption = GetLROOptions(); if (lroOption.Length == 0) { return(builder.AppendLine("{0}.get_long_running_operation_result(response, deserialize_method)", clientReference).ToString()); } return(builder.AppendLine("{0}.get_long_running_operation_result(response, deserialize_method, {1})", clientReference, lroOption).ToString()); }
/// <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()); }
private void ReplacePathParametersInUri(string variableName, IndentedStringBuilder builder) { foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path)) { string replaceString = "{0} = {0}.Replace(\"{{{1}}}\", System.Uri.EscapeDataString({2}));"; if (pathParameter.Extensions.ContainsKey(AzureExtensions.SkipUrlEncodingExtension)) { replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } builder.AppendLine(replaceString, variableName, pathParameter.SerializedName, pathParameter.ModelType.ToString(ClientReference, pathParameter.Name)); } }
public void AppendMultilinePreservesIndentation() { IndentedStringBuilder sb = new IndentedStringBuilder(); var expected = string.Format("start{0} line2{0} line31{0} line32{0}", Environment.NewLine); var result = sb .AppendLine("start").Indent() .AppendLine("line2").Indent() .AppendLine(string.Format("line31{0}line32", Environment.NewLine)); Assert.Equal(expected, result.ToString()); sb = new IndentedStringBuilder(); expected = string.Format("start{0} line2{0} line31{0} line32{0}", Environment.NewLine); result = sb .AppendLine("start").Indent() .AppendLine("line2").Indent() .AppendLine(string.Format("line31{0}line32", Environment.NewLine)); Assert.Equal(expected, result.ToString()); }
/// <summary> /// Returns generated response or body of the auto-paginated method. /// </summary> public override string ResponseGeneration() { IndentedStringBuilder builder = new IndentedStringBuilder(); if (ReturnType.Body != null) { if (ReturnType.Body is CompositeType) { CompositeType compositeType = (CompositeType)ReturnType.Body; if (compositeType.Extensions.ContainsKey(AzureExtensions.PageableExtension) && this.Extensions.ContainsKey("nextMethodName")) { bool isNextLinkMethod = this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"]; bool isPageable = (bool)compositeType.Extensions[AzureExtensions.PageableExtension]; if (isPageable && !isNextLinkMethod) { builder.AppendLine("first_page = {0}_as_lazy({1})", Name, MethodParameterInvocation); builder.AppendLine("first_page.get_all_items"); return(builder.ToString()); } } } } return(base.ResponseGeneration()); }
/// <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); RemoveDuplicateForwardSlashes("requestUrl", builder); if (HasQueryParameters()) { BuildQueryParameterArray(builder); AddQueryParametersToUrl(variableName, builder); } 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(); }
private static void AppendConstraintValidations(string valueReference, Dictionary<Constraint, string> constraints, IndentedStringBuilder sb, KnownFormat format) { foreach (var constraint in constraints.Keys) { string constraintCheck; string constraintValue = (format == KnownFormat.@char) ?$"'{constraints[constraint]}'" : constraints[constraint]; switch (constraint) { case Constraint.ExclusiveMaximum: constraintCheck = $"{valueReference} >= {constraintValue}"; break; case Constraint.ExclusiveMinimum: constraintCheck = $"{valueReference} <= {constraintValue}"; break; case Constraint.InclusiveMaximum: constraintCheck = $"{valueReference} > {constraintValue}"; break; case Constraint.InclusiveMinimum: constraintCheck = $"{valueReference} < {constraintValue}"; break; case Constraint.MaxItems: constraintCheck = $"{valueReference}.Count > {constraintValue}"; break; case Constraint.MaxLength: constraintCheck = $"{valueReference}.Length > {constraintValue}"; break; case Constraint.MinItems: constraintCheck = $"{valueReference}.Count < {constraintValue}"; break; case Constraint.MinLength: constraintCheck = $"{valueReference}.Length < {constraintValue}"; break; case Constraint.MultipleOf: constraintCheck = $"{valueReference} % {constraintValue} != 0"; break; case Constraint.Pattern: constraintValue = $"\"{constraintValue.Replace("\\", "\\\\")}\""; constraintCheck = $"!System.Text.RegularExpressions.Regex.IsMatch({valueReference}, {constraintValue})"; break; case Constraint.UniqueItems: if ("true".EqualsIgnoreCase(constraints[constraint])) { constraintCheck = $"{valueReference}.Count != {valueReference}.Distinct().Count()"; } else { constraintCheck = null; } break; default: throw new NotSupportedException("Constraint '" + constraint + "' is not supported."); } if (constraintCheck != null) { if (constraint != Constraint.UniqueItems) { sb.AppendLine("if ({0})", constraintCheck) .AppendLine("{").Indent() .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\", {2});", constraint, valueReference.Replace("this.", ""), constraintValue).Outdent() .AppendLine("}"); } else { sb.AppendLine("if ({0})", constraintCheck) .AppendLine("{").Indent() .AppendLine("throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.{0}, \"{1}\");", constraint, valueReference.Replace("this.", "")).Outdent() .AppendLine("}"); } } } }
private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvider scope, string valueReference, bool isRequired) { if (scope == null) { throw new ArgumentNullException("scope"); } if (primary == null) { throw new ArgumentNullException("primary"); } var builder = new IndentedStringBuilder(" "); var requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type {1}.');"; var typeErrorMessage = "throw new Error('{0} must be of type {1}.');"; var lowercaseTypeName = primary.Name.ToLower(CultureInfo.InvariantCulture); if (primary.Type == KnownPrimaryType.Boolean || primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Object) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0} !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.Stream) { if (isRequired) { builder.AppendLine("if ({0} === null || {0} === undefined) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.String) { if (isRequired) { //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} !== null && {0} !== undefined && typeof {0}.valueOf() !== '{1}') {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.Uuid) { if (isRequired) { requiredTypeErrorMessage = "throw new Error('{0} cannot be null or undefined and it must be of type string and must be a valid {1}.');"; //empty string can be a valid value hence we cannot implement the simple check if (!{0}) builder.AppendLine("if ({0} === null || {0} === undefined || typeof {0}.valueOf() !== 'string' || !msRest.isValidUuid({0})) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } typeErrorMessage = "throw new Error('{0} must be of type string and must be a valid {1}.');"; builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) { if (isRequired) { builder.AppendLine("if (!Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTimeRfc1123 || primary.Type == KnownPrimaryType.UnixTime) { if (isRequired) { builder.AppendLine("if(!{0} || !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder = builder.AppendLine("if ({0} && !({0} instanceof Date || ", valueReference) .Indent() .Indent() .AppendLine("(typeof {0}.valueOf() === 'string' && !isNaN(Date.parse({0}))))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else if (primary.Type == KnownPrimaryType.TimeSpan) { if (isRequired) { builder.AppendLine("if(!{0} || !moment.isDuration({0})) {{", valueReference); return ConstructValidationCheck(builder, requiredTypeErrorMessage, valueReference, primary.Name).ToString(); } builder.AppendLine("if({0} && !moment.isDuration({0})) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } else { throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "'{0}' not implemented", valueReference)); } }
/// <summary> /// Generate code to remove duplicated forward slashes from a URL in code /// </summary> /// <param name="urlVariableName"></param> /// <param name="builder">The stringbuilder for url construction</param> /// <returns></returns> public virtual string RemoveDuplicateForwardSlashes(string urlVariableName, IndentedStringBuilder builder) { builder.AppendLine("// trim all duplicate forward slashes in the url"); builder.AppendLine("var regex = /([^:]\\/)\\/+/gi;"); builder.AppendLine("{0} = {0}.replace(regex, '$1');", urlVariableName); return builder.ToString(); }
/// <summary> /// Genrate code to build an array of query parameter strings in a variable named 'queryParameters'. The /// array should contain one string element for each query parameter of the form 'key=value' /// </summary> /// <param name="builder">The stringbuilder for url construction</param> protected virtual void BuildQueryParameterArray(IndentedStringBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } builder.AppendLine("var queryParameters = [];"); foreach (var queryParameter in LogicalParameters .Where(p => p.Location == ParameterLocation.Query)) { var queryAddFormat = "queryParameters.push('{0}=' + encodeURIComponent({1}));"; if (queryParameter.SkipUrlEncoding()) { queryAddFormat = "queryParameters.push('{0}=' + {1});"; } if (!queryParameter.IsRequired) { builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", queryParameter.Name) .Indent() .AppendLine(queryAddFormat, queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue()).Outdent() .AppendLine("}"); } else { builder.AppendLine(queryAddFormat, queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue()); } } }
public string ConstructTSItemTypeName() { var builder = new IndentedStringBuilder(" "); builder.AppendFormat("<{0}>", ItemType.Name); return builder.ToString(); }
public static string ConstructPropertyDocumentation(string propertyDocumentation) { var builder = new IndentedStringBuilder(" "); return builder.AppendLine(propertyDocumentation) .AppendLine(" * ").ToString(); }
/// <summary> /// Generates Ruby code in form of string for deserializing object of given type. /// </summary> /// <param name="type">Type of object needs to be deserialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to be deserialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureDeserializeType( this IModelType type, IChild scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var enumType = type as EnumTypeRb; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.KnownPrimaryType == KnownPrimaryType.Int || primary.KnownPrimaryType == KnownPrimaryType.Long) { return builder.AppendLine("{0} = Integer({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.Double) { return builder.AppendLine("{0} = Float({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_decode64({0}).unpack('C*') unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.Date) { return builder.AppendLine("{0} = MsRest::Serialization.deserialize_date({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.DateTime) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = DateTime.parse({0}) unless {0}.to_s.empty?", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime) { return builder.AppendLine("{0} = DateTime.strptime({0}.to_s, '%s') unless {0}.to_s.empty?", valueReference).ToString(); } } else if (enumType != null && !string.IsNullOrEmpty(enumType.Name)) { return builder .AppendLine("if (!{0}.nil? && !{0}.empty?)", valueReference) .AppendLine( " enum_is_valid = {0}.constants.any? {{ |e| {0}.const_get(e).to_s.downcase == {1}.downcase }}", enumType.ModuleName, valueReference) .AppendLine( " warn 'Enum {0} does not contain ' + {1}.downcase + ', but was received from the server.' unless enum_is_valid", enumType.ModuleName, valueReference) .AppendLine("end") .ToString(); } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureDeserializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("deserialized_{0} = []", sequence.Name.ToLower()) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("deserialized_{0}.push({1})", sequence.Name.ToLower(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = deserialized_{1}", valueReference, sequence.Name.ToLower()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureDeserializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each do |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("end") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { var compositeName = composite.Name; if(compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.deserialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
public string ConstructTSItemTypeName() { var builder = new IndentedStringBuilder(" "); builder.AppendFormat("<{0}>", ClientModelExtensions.TSType(ItemType, true)); return builder.ToString(); }
/// <summary> /// Generates Ruby code in form of string for serializing object of given type. /// </summary> /// <param name="type">Type of object needs to be serialized.</param> /// <param name="scope">Current scope.</param> /// <param name="valueReference">Reference to object which needs to serialized.</param> /// <returns>Generated Ruby code in form of string.</returns> public static string AzureSerializeType( this IModelType type, IChild scope, string valueReference) { var composite = type as CompositeType; var sequence = type as SequenceType; var dictionary = type as DictionaryType; var primary = type as PrimaryType; var builder = new IndentedStringBuilder(" "); if (primary != null) { if (primary.KnownPrimaryType == KnownPrimaryType.ByteArray) { return builder.AppendLine("{0} = Base64.strict_encode64({0}.pack('c*'))", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.DateTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%FT%TZ')", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.DateTimeRfc1123) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%a, %d %b %Y %H:%M:%S GMT')", valueReference).ToString(); } if (primary.KnownPrimaryType == KnownPrimaryType.UnixTime) { return builder.AppendLine("{0} = {0}.new_offset(0).strftime('%s')", valueReference).ToString(); } } else if (sequence != null) { var elementVar = scope.GetUniqueName("element"); var innerSerialization = sequence.ElementType.AzureSerializeType(scope, elementVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder .AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("serialized{0} = []", sequence.Name) .AppendLine("{0}.each do |{1}|", valueReference, elementVar) .Indent() .AppendLine(innerSerialization) .AppendLine("serialized{0}.push({1})", sequence.Name.ToPascalCase(), elementVar) .Outdent() .AppendLine("end") .AppendLine("{0} = serialized{1}", valueReference, sequence.Name.ToPascalCase()) .Outdent() .AppendLine("end") .ToString(); } } else if (dictionary != null) { var valueVar = scope.GetUniqueName("valueElement"); var innerSerialization = dictionary.ValueType.AzureSerializeType(scope, valueVar); if (!string.IsNullOrEmpty(innerSerialization)) { return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0}.each {{ |key, {1}|", valueReference, valueVar) .Indent() .AppendLine(innerSerialization) .AppendLine("{0}[key] = {1}", valueReference, valueVar) .Outdent() .AppendLine("}") .Outdent() .AppendLine("end").ToString(); } } else if (composite != null) { var compositeName = composite.Name; if(compositeName == "Resource" || compositeName == "SubResource") { compositeName = string.Format(CultureInfo.InvariantCulture, "{0}::{1}", "MsRestAzure", compositeName); } return builder.AppendLine("unless {0}.nil?", valueReference) .Indent() .AppendLine("{0} = {1}.serialize_object({0})", valueReference, compositeName) .Outdent() .AppendLine("end").ToString(); } return string.Empty; }
public string ConstructImportTS() { IndentedStringBuilder builder = new IndentedStringBuilder(IndentedStringBuilder.TwoSpaces); builder.Append("import { ServiceClientOptions, RequestOptions, ServiceCallback"); if (Properties.Any(p => p.Name.Equals("credentials", StringComparison.InvariantCultureIgnoreCase))) { builder.Append(", ServiceClientCredentials"); } builder.Append(" } from 'ms-rest';"); return builder.ToString(); }
protected override void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false) { if (this.InputParameterTransformation.IsNullOrEmpty() || nextMethod.InputParameterTransformation.IsNullOrEmpty()) { return; } var groupedType = this.InputParameterTransformation.First().ParameterMappings[0].InputParameter; var nextGroupType = nextMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter; if (nextGroupType.Name == groupedType.Name) { return; } var nextGroupTypeName = _namer.GetTypeName(nextGroupType.Name) + "Inner"; if (filterRequired && !groupedType.IsRequired) { return; } if (!groupedType.IsRequired) { builder.AppendLine("{0} {1} = null;", nextGroupTypeName, nextGroupType.Name.ToCamelCase()); builder.AppendLine("if ({0} != null) {{", groupedType.Name.ToCamelCase()); builder.Indent(); builder.AppendLine("{0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName); } else { builder.AppendLine("{1} {0} = new {1}();", nextGroupType.Name.ToCamelCase(), nextGroupTypeName); } foreach (var outParam in nextMethod.InputParameterTransformation.Select(t => t.OutputParameter)) { builder.AppendLine("{0}.with{1}({2}.{3}());", nextGroupType.Name.ToCamelCase(), outParam.Name.ToPascalCase(), groupedType.Name.ToCamelCase(), outParam.Name.ToCamelCase()); } if (!groupedType.IsRequired) { builder.Outdent().AppendLine(@"}"); } }
public string 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 static string Fields(this CompositeType compositeType) { var indented = new IndentedStringBuilder(" "); var properties = compositeType.Properties; if (compositeType.BaseModelType != null) { indented.Append(compositeType.BaseModelType.Fields()); } // If the type is a paged model type, ensure the nextLink field exists // Note: Inject the field into a copy of the property list so as to not pollute the original list if ( compositeType is ModelTemplateModel && !String.IsNullOrEmpty((compositeType as ModelTemplateModel).NextLink)) { var nextLinkField = (compositeType as ModelTemplateModel).NextLink; foreach (Property p in properties) { p.Name = GoCodeNamer.PascalCaseWithoutChar(p.Name, '.'); if (p.Name.Equals(nextLinkField, StringComparison.OrdinalIgnoreCase)) { p.Name = nextLinkField; } } if (!properties.Any(p => p.Name.Equals(nextLinkField, StringComparison.OrdinalIgnoreCase))) { var property = new Property(); property.Name = nextLinkField; property.Type = new PrimaryType(KnownPrimaryType.String) { Name = "string" }; properties = new List<Property>(properties); properties.Add(property); } } // Emit each property, except for named Enumerated types, as a pointer to the type foreach (var property in properties) { EnumType enumType = property.Type as EnumType; if (enumType != null && enumType.IsNamed()) { indented.AppendFormat("{0} {1} {2}\n", property.Name, enumType.Name, property.JsonTag()); } else if (property.Type is DictionaryType) { indented.AppendFormat("{0} *{1} {2}\n", property.Name, (property.Type as MapType).FieldName, property.JsonTag()); } else { indented.AppendFormat("{0} *{1} {2}\n", property.Name, property.Type.Name, property.JsonTag()); } } return indented.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(); }
public static string ConstructParameterDocumentation(string documentation) { var builder = new IndentedStringBuilder(" "); return builder.AppendLine(documentation) .AppendLine(" * ").ToString(); }
/// <summary> /// Generate code to replace path parameters in the url template with the appropriate values /// </summary> /// <param name="variableName">The variable name for the url to be constructed</param> /// <param name="builder">The string builder for url construction</param> protected virtual void BuildPathParameters(string variableName, IndentedStringBuilder builder) { if (builder == null) { throw new ArgumentNullException("builder"); } foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path)) { var pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', encodeURIComponent({2}));"; if (pathParameter.SkipUrlEncoding()) { pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});"; } var urlPathName = pathParameter.SerializedName; string pat = @".*\{" + urlPathName + @"(\:\w+)\}"; Regex r = new Regex(pat); Match m = r.Match(Url); if (m.Success) { urlPathName += m.Groups[1].Value; } builder.AppendLine(pathReplaceFormat, variableName, urlPathName, pathParameter.Type.ToString(pathParameter.Name)); } }
public virtual string BuildFlattenParameterMappings() { var builder = new IndentedStringBuilder(); foreach (var transformation in InputParameterTransformation) { builder.AppendLine("var {0};", transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", BuildNullCheckExpression(transformation)) .Indent(); if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) && transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0} = new client.models['{1}']();", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1};", transformation.OutputParameter.Name, mapping); } builder.Outdent() .AppendLine("}"); } return builder.ToString(); }
/// <summary> /// 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(); }
private static string ValidateSequenceType(this SequenceType sequence, IScopeProvider scope, string valueReference, bool isRequired, string modelReference = "client.models") { if (scope == null) { throw new ArgumentNullException("scope"); } var builder = new IndentedStringBuilder(" "); var escapedValueReference = valueReference.EscapeSingleQuotes(); var indexVar = scope.GetUniqueName("i"); var innerValidation = sequence.ElementType.ValidateType(scope, valueReference + "[" + indexVar + "]", false, modelReference); if (!string.IsNullOrEmpty(innerValidation)) { if (isRequired) { return builder.AppendLine("if (!util.isArray({0})) {{", valueReference) .Indent() .AppendLine("throw new Error('{0} cannot be null or undefined and it must be of type {1}.');", escapedValueReference, sequence.Name.ToLower(CultureInfo.InvariantCulture)) .Outdent() .AppendLine("}") .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}").ToString(); } return builder.AppendLine("if (util.isArray({0})) {{", valueReference) .Indent() .AppendLine("for (var {1} = 0; {1} < {0}.length; {1}++) {{", valueReference, indexVar) .Indent() .AppendLine(innerValidation) .Outdent() .AppendLine("}") .Outdent() .AppendLine("}").ToString(); } return null; }
/// <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(); }
///////////////////////////////////////////////////////////////////////////////////////// // // Parameter Extensions // ///////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Return a Go map of required parameters. /// </summary> /// <param name="parameters"></param> /// <param name="mapVariable"></param> /// <returns></returns> public static string BuildParameterMap(this IEnumerable<Parameter> parameters, string mapVariable) { var builder = new StringBuilder(); builder.Append(mapVariable); builder.Append(" := map[string]interface{} {"); if (parameters.Count() > 0) { builder.AppendLine(); var indented = new IndentedStringBuilder(" "); parameters .Where(p => p.IsRequired) .OrderBy(p => p.SerializedName) .ForEach(p => indented.AppendLine("\"{0}\": {1},", p.NameForMap(), p.ValueForMap())); builder.Append(indented); } builder.AppendLine("}"); return builder.ToString(); }
/// <summary> /// Generate code to perform required validation on a type /// </summary> /// <param name="type">The type to validate</param> /// <param name="scope">A scope provider for generating variable names as necessary</param> /// <param name="valueReference">A reference to the value being validated</param> /// <param name="constraints">Constraints</param> /// <returns>The code to validate the reference of the given type</returns> public static string ValidateType(this IModelType type, IChild scope, string valueReference, Dictionary<Constraint, string> constraints) { if (scope == null) { throw new ArgumentNullException("scope"); } var model = type as CompositeTypeCs; var sequence = type as SequenceTypeCs; var dictionary = type as DictionaryTypeCs; var sb = new IndentedStringBuilder(); if (model != null && model.ShouldValidateChain()) { sb.AppendLine("{0}.Validate();", valueReference); } if (constraints != null && constraints.Any()) { AppendConstraintValidations(valueReference, constraints, sb, (type as PrimaryType)?.KnownFormat ?? KnownFormat.none); } if (sequence != null && sequence.ShouldValidateChain()) { var elementVar = scope.GetUniqueName("element"); var innerValidation = sequence.ElementType.ValidateType(scope, elementVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1})", elementVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}"); } } else if (dictionary != null && dictionary.ShouldValidateChain()) { var valueVar = scope.GetUniqueName("valueElement"); var innerValidation = dictionary.ValueType.ValidateType(scope, valueVar, null); if (!string.IsNullOrEmpty(innerValidation)) { sb.AppendLine("foreach (var {0} in {1}.Values)", valueVar, valueReference) .AppendLine("{").Indent() .AppendLine(innerValidation).Outdent() .AppendLine("}").Outdent(); } } if (sb.ToString().Trim().Length > 0) { if (type.IsValueType()) { return sb.ToString(); } else { return CheckNull(valueReference, sb.ToString()); } } return null; }