public string GenerateOperationSpecDefinitions(string emptyLine)
        {
            TSBuilder builder = new TSBuilder();

            builder.LineComment("Operation Specifications");
            bool addedFirstValue = false;

            foreach (MethodTS method in MethodTemplateModels)
            {
                if (!method.IsLongRunningOperation)
                {
                    if (addedFirstValue)
                    {
                        builder.Line(emptyLine);
                    }
                    else
                    {
                        builder.ConstObjectVariable("serializer", ClientModelExtensions.CreateSerializerExpression(this));
                        addedFirstValue = true;
                    }
                    method.GenerateOperationSpecDefinition(builder);
                }
            }

            return(builder.ToString());
        }
        public string GenerateParameterMappers()
        {
            TSBuilder builder = new TSBuilder();
            IEnumerable <ParameterTS> parameters = Methods
                                                   .SelectMany(m => m.LogicalParameters)
                                                   .Cast <ParameterTS>()
                                                   .Where(p => p.ModelTypeName != "RequestOptionsBase" && p.Location != ParameterLocation.Body)
                                                   .OrderBy(p => p.MapperName)
                                                   .Distinct(ParameterNameComparer.Instance);

            foreach (ParameterTS parameter in parameters)
            {
                string parameterInterfaceName =
                    parameter.Location == ParameterLocation.Path ? "msRest.OperationURLParameter" :
                    parameter.Location == ParameterLocation.Query ? "msRest.OperationQueryParameter" :
                    "msRest.OperationParameter";

                builder.Text("export ");
                builder.ConstObjectVariable(
                    parameter.MapperName,
                    parameterInterfaceName,
                    obj => ClientModelExtensions.ConstructParameterMapper(obj, parameter));
                builder.Line();
            }

            return(builder.ToString());
        }
Exemple #3
0
        public virtual string InitializeProperty(Property modelProperty)
        {
            if (modelProperty == null || modelProperty.ModelType == null)
            {
                throw new ArgumentNullException("modelProperty");
            }

            string xmlDeclarations = "";

            if (CodeModel.ShouldGenerateXmlSerialization)
            {
                List <string> combinedXmlDeclarations = GenericXmlCtxtSerializer.XmlSerializationPropertyCtxt(modelProperty);

                SequenceTypePy sequenceType = modelProperty.ModelType as SequenceTypePy;
                if (sequenceType != null && !string.IsNullOrEmpty(sequenceType.ElementXmlName))
                {
                    combinedXmlDeclarations.AddRange(sequenceType.ItemsSerializationContext());
                }

                xmlDeclarations = string.Format(CultureInfo.InvariantCulture,
                                                ", 'xml': {{{1}}}",
                                                modelProperty.Name,
                                                string.Join(", ", combinedXmlDeclarations)
                                                );
            }

            //'id':{'key':'id', 'type':'str'},
            return(string.Format(CultureInfo.InvariantCulture,
                                 "'{0}': {{'key': '{1}', 'type': '{2}'{3}}},",
                                 modelProperty.Name,
                                 modelProperty.SerializedName,
                                 ClientModelExtensions.GetPythonSerializationType(modelProperty.ModelType),
                                 xmlDeclarations
                                 ));
        }
        public string ConstructTSItemTypeName()
        {
            var builder = new IndentedStringBuilder("  ");

            builder.AppendFormat("<{0}>", ClientModelExtensions.TSType(ItemType, true));
            return(builder.ToString());
        }
        public override void GenerateModelDefinition(TSBuilder builder)
        {
            builder.DocumentationComment(comment =>
            {
                comment.Summary(Summary);
                comment.Description(Documentation);
            });

            IModelType arrayType;
            Property   arrayProperty = Properties.FirstOrDefault(p => p.ModelType is SequenceTypeJs);

            if (arrayProperty == null)
            {
                throw new Exception($"The Pageable model {Name} does not contain a single property that is an Array.");
            }
            else
            {
                arrayType = ((SequenceTypeJs)arrayProperty.ModelType).ElementType;
            }

            builder.ExportInterface(Name, $"Array<{ClientModelExtensions.TSType(arrayType, true)}>", tsInterface =>
            {
                Property nextLinkProperty = Properties.Where(p => p.Name.ToLowerInvariant().Contains("nextlink")).FirstOrDefault();
                if (nextLinkProperty != null)
                {
                    tsInterface.DocumentationComment(comment =>
                    {
                        comment.Summary(nextLinkProperty.Summary);
                        comment.Description(nextLinkProperty.Documentation);
                    });
                    string propertyType = nextLinkProperty.ModelType.TSType(inModelsModule: true);
                    tsInterface.Property(nextLinkProperty.Name, propertyType, isRequired: nextLinkProperty.IsRequired, isReadonly: nextLinkProperty.IsReadOnly);
                }
            });
        }
Exemple #6
0
        public string GetDeserializationString(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
        {
            TSBuilder builder = new TSBuilder();

            if (type is CompositeType)
            {
                builder.Line($"const resultMapper = Mappers.{type.Name};");
            }
            else
            {
                builder.Text($"const resultMapper = ");
                ClientModelExtensions.ConstructMapper(builder, type, responseVariable, null, isPageable: false, expandComposite: false, isXML: CodeModel?.ShouldGenerateXmlSerialization == true);
                builder.Line(";");
            }

            if (CodeModel.ShouldGenerateXmlSerialization && type is SequenceType st)
            {
                builder.Line("{2} = client.serializer.deserialize(resultMapper, typeof {0} === 'object' ? {0}['{1}'] : [], '{2}');", responseVariable, st.ElementType.XmlName, valueReference);
            }
            else
            {
                builder.Line("{1} = client.serializer.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
            }
            return(builder.ToString());
        }
        public virtual string ConstructModelMapper()
        {
            var modelMapper = ClientModelExtensions.ConstructMapper(this, SerializedName, null, false, true);
            var builder     = new IndentedStringBuilder("  ");

            builder.AppendLine("return {{{0}}};", modelMapper);
            return(builder.ToString());
        }
        public override string ConstructModelMapper()
        {
            TSBuilder builder = new TSBuilder();

            builder.Text($"export const {Name} = ");
            ClientModelExtensions.ConstructMapper(builder, this, SerializedName, null, isPageable: true, expandComposite: true, isXML: CodeModel?.ShouldGenerateXmlSerialization == true);
            builder.Line(";");
            return(builder.ToString());
        }
        public virtual void ConstructModelMapper(TSBuilder builder)
        {
            builder.Text($"export const {Name}: coreHttp.CompositeMapper = ");
            bool isHeaders = CodeModel.HeaderTypes.Contains(this) == true;
            bool isXML     = !isHeaders && CodeModel.ShouldGenerateXmlSerialization == true;

            ClientModelExtensions.ConstructMapper(builder, this, SerializedName, null, isPageable: false, expandComposite: true, isXML: isXML, isCaseSensitive: !isHeaders, xmlName: isXML ? XmlName : null);
            builder.Line(";");
        }
        public virtual string ConstructModelMapper()
        {
            TSBuilder builder = new TSBuilder();

            builder.Text($"export const {Name} = ");
            bool isXML = CodeModel?.ShouldGenerateXmlSerialization == true;

            ClientModelExtensions.ConstructMapper(builder, this, SerializedName, null, isPageable: false, expandComposite: true, isXML: isXML, isCaseSensitive: CodeModel?.HeaderTypes.Contains(this) != true, xmlName: isXML ? XmlName : null);
            builder.Line(";");
            return(builder.ToString());
        }
Exemple #11
0
        public void GenerateOperationSpec(TSObject operationSpec)
        {
            operationSpec.QuotedStringProperty("httpMethod", HttpMethod.ToString().ToUpper());
            if (IsAbsoluteUrl)
            {
                operationSpec.QuotedStringProperty("baseUrl", CodeModelTS.SchemeHostAndPort);
            }
            else
            {
                operationSpec.TextProperty("baseUrl", $"{ClientReference}.baseUri");
            }

            string path = Path;

            if (!string.IsNullOrEmpty(path))
            {
                operationSpec.QuotedStringProperty("path", path);
            }

            Parameter[] logicalParameters = LogicalParameters.ToArray();
            GenerateParameters(operationSpec, "urlParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Path), AddSkipEncodingProperty);
            GenerateParameters(operationSpec, "queryParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Query),
                               (TSObject queryParameterObject, Parameter queryParameter) =>
            {
                AddSkipEncodingProperty(queryParameterObject, queryParameter);
                if (queryParameter.CollectionFormat != CollectionFormat.None)
                {
                    queryParameterObject.TextProperty("collectionFormat", $"msRest.QueryCollectionFormat.{queryParameter.CollectionFormat}");
                }
            });
            GenerateParameters(operationSpec, "headerParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Header));

            if (RequestBody != null)
            {
                operationSpec.Property("requestBodyMapper", requestBodyMapper => ClientModelExtensions.ConstructRequestBodyMapper(requestBodyMapper, RequestBody));
                operationSpec.QuotedStringProperty("requestBodyName", RequestBody.Name);
                operationSpec.QuotedStringProperty("contentType", RequestContentType);
            }
            else
            {
                IEnumerable <Parameter> formDataParameters = logicalParameters.Where(p => p.Location == ParameterLocation.FormData);
                if (formDataParameters.Any())
                {
                    GenerateParameters(operationSpec, "formDataParameters", formDataParameters);
                    operationSpec.QuotedStringProperty("contentType", RequestContentType);
                }
            }

            if (CodeModel.ShouldGenerateXmlSerialization)
            {
                operationSpec.BooleanProperty("isXML", true);
            }
        }
Exemple #12
0
        public virtual string InitializeProperty(Property modelProperty)
        {
            if (modelProperty == null || modelProperty.ModelType == null)
            {
                throw new ArgumentNullException("modelProperty");
            }

            //'id':{'key':'id', 'type':'str'},
            return(string.Format(CultureInfo.InvariantCulture,
                                 "'{0}': {{'key': '{1}', 'type': '{2}'}},",
                                 modelProperty.Name, modelProperty.SerializedName,
                                 ClientModelExtensions.GetPythonSerializationType(modelProperty.ModelType)));
        }
Exemple #13
0
        public void DeserializeResponse(TSBlock block, IModelType type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            const string responseVariable = "parsedResponse";
            const string valueReference   = "operationRes.parsedBody";

            block.Line($"let {responseVariable} = {valueReference} as {{ [key: string]: any }};");
            block.If($"{responseVariable} != undefined", ifBlock =>
            {
                ifBlock.Try(tryBlock =>
                {
                    tryBlock.ConstObjectVariable("serializer", CodeModel.CreateSerializerExpression());
                    tryBlock.Text($"{valueReference} = ");
                    tryBlock.FunctionCall("serializer.deserialize", argumentList =>
                    {
                        string expressionToDeserialize = responseVariable;

                        if (type is CompositeType)
                        {
                            argumentList.Text($"Mappers.{type.Name}");
                        }
                        else
                        {
                            bool isXml = CodeModel?.ShouldGenerateXmlSerialization == true;
                            if (isXml && type is SequenceType st)
                            {
                                expressionToDeserialize = $"typeof {responseVariable} === \"object\" ? {responseVariable}[\"{st.ElementType.XmlName}\"] : []";
                            }

                            ClientModelExtensions.ConstructMapper(argumentList, type, responseVariable, null, isPageable: false, expandComposite: false, isXML: isXml);
                        }

                        argumentList.Text(expressionToDeserialize);

                        argumentList.QuotedString(valueReference);
                    });
                })
                .Catch("error", catchBlock =>
                {
                    string errorVariable = this.GetUniqueName("deserializationError");
                    catchBlock.Line($"const {errorVariable} = new msRest.RestError(`Error ${{error}} occurred in deserializing the responseBody - ${{operationRes.bodyAsText}}`);");
                    catchBlock.Line($"{errorVariable}.request = msRest.stripRequest(httpRequest);");
                    catchBlock.Line($"{errorVariable}.response = msRest.stripResponse(operationRes);");
                    catchBlock.Throw(errorVariable);
                });
            });
Exemple #14
0
        public string GetDeserializationString(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
        {
            var builder = new IndentedStringBuilder("  ");

            if (type is CompositeType)
            {
                builder.AppendLine("let resultMapper = new client.models['{0}']().mapper();", type.Name);
            }
            else
            {
                builder.AppendLine("let resultMapper = {{{0}}};", ClientModelExtensions.ConstructMapper(type, responseVariable, null, false, false));
            }
            builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
            return(builder.ToString());
        }
        public override string InitializeProperty(Property modelProperty)
        {
            if (modelProperty == null || modelProperty.Type == null)
            {
                throw new ArgumentNullException("modelProperty");
            }

            if (Azure.AzureExtensions.IsAzureResource(this) && modelProperty.SerializedName.Contains("properties."))
            {
                return(string.Format(CultureInfo.InvariantCulture,
                                     "'{0}': {{'key': '{1}', 'type': '{2}', 'flatten': True}},",
                                     modelProperty.Name, modelProperty.SerializedName,
                                     ClientModelExtensions.GetPythonSerializationType(modelProperty.Type)));
            }
            return(base.InitializeProperty(modelProperty));
        }
Exemple #16
0
        /// <remarks>
        /// Used in Python 3, Python 2 doesn't have typehing * syntax
        /// </remarks>
        public virtual string ModelParameterDeclaration()
        {
            List <string> declarations         = new List <string>();
            List <string> requiredDeclarations = new List <string>();
            List <string> combinedDeclarations = new List <string>();

            foreach (var property in ComposedProperties.Except(ReadOnlyAttributes).Where(each => !each.IsPolymorphicDiscriminator))
            {
                if (this.BaseIsPolymorphic)
                {
                    if (property.Name == this.BasePolymorphicDiscriminator)
                    {
                        continue;
                    }
                }

                string typeHint = ClientModelExtensions.GetPythonTypeHint(property.ModelType) ?? "";
                if (typeHint != "")
                {
                    typeHint = ": " + typeHint;
                }
                if (property.IsRequired && property.DefaultValue.RawValue.IsNullOrEmpty())
                {
                    requiredDeclarations.Add($"{property.Name}{typeHint}");
                }
                else
                {
                    declarations.Add($"{property.Name}{typeHint}={property.DefaultValue}");
                }
            }

            if (requiredDeclarations.Any())
            {
                combinedDeclarations.Add(string.Join(", ", requiredDeclarations));
            }
            if (declarations.Any())
            {
                combinedDeclarations.Add(string.Join(", ", declarations));
            }

            if (!combinedDeclarations.Any())
            {
                return(", **kwargs");
            }
            return(", *, " + string.Join(", ", combinedDeclarations) + ", **kwargs");
        }
        private static string BuildSerializeDataCall(Parameter parameter, string functionName)
        {
            string divChar      = ClientModelExtensions.NeedsFormattedSeparator(parameter);
            string divParameter = string.Empty;

            if (!string.IsNullOrEmpty(divChar))
            {
                divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar);
            }

            return(string.Format(CultureInfo.InvariantCulture,
                                 "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4})",
                                 functionName,
                                 parameter.Name,
                                 parameter.Type.ToPythonRuntimeTypeString(),
                                 parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty,
                                 divParameter));
        }
Exemple #18
0
 private static void GenerateParameters(TSObject operationSpec, string propertyName, IEnumerable <Parameter> parameters, Action <TSObject, Parameter> extraParameterProperties = null)
 {
     if (parameters != null && parameters.Any())
     {
         operationSpec.ArrayProperty(propertyName, parameterArray =>
         {
             foreach (ParameterTS parameter in parameters)
             {
                 parameterArray.Object(parameterObject =>
                 {
                     parameterObject.QuotedStringProperty("parameterName", parameter.Name);
                     extraParameterProperties?.Invoke(parameterObject, parameter);
                     parameterObject.Property("mapper", mapper => ClientModelExtensions.ConstructMapper(mapper, parameter.ModelType, parameter.SerializedName, parameter, false, false, false));
                 });
             }
         });
     }
 }
        internal static void GenerateRequestParameter(TSObject parameterObject, ParameterTS requestParameter, ParameterTransformations parameterTransformations)
        {
            GenerateRequestParameterPath(parameterObject, requestParameter, parameterTransformations);
            parameterObject.Property("mapper", mapper => ClientModelExtensions.ConstructMapper(mapper, requestParameter.ModelType, requestParameter.SerializedName, requestParameter, false, false, false));

            ParameterLocation location = requestParameter.Location;

            if (location == ParameterLocation.Path || location == ParameterLocation.Query)
            {
                AddSkipEncodingProperty(parameterObject, requestParameter);
            }
            if (location == ParameterLocation.Query)
            {
                if (requestParameter.CollectionFormat != CollectionFormat.None)
                {
                    parameterObject.TextProperty("collectionFormat", $"msRest.QueryCollectionFormat.{requestParameter.CollectionFormat}");
                }
            }
        }
        private static string BuildSerializeDataCall(Parameter parameter, string functionName)
        {
            string divChar      = ClientModelExtensions.NeedsFormattedSeparator(parameter);
            string divParameter = string.Empty;

            if (!string.IsNullOrEmpty(divChar))
            {
                divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar);
            }

            //TODO: This creates a very long line - break it up over multiple lines.
            return(string.Format(CultureInfo.InvariantCulture,
                                 "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4}{5})",
                                 functionName,
                                 parameter.Name,
                                 parameter.Type.ToPythonRuntimeTypeString(),
                                 parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty,
                                 divParameter,
                                 BuildValidationParameters(parameter.Constraints)));
        }
Exemple #21
0
        private string BuildSerializeDataCall(Parameter parameter, string functionName)
        {
            string divChar      = ClientModelExtensions.NeedsFormattedSeparator(parameter);
            string divParameter = string.Empty;

            string parameterName = (MethodGroup as MethodGroupPy)?.ConstantProperties?.FirstOrDefault(each => each.Name.RawValue == parameter.Name.RawValue && each.DefaultValue.RawValue == parameter.DefaultValue.RawValue)?.Name.Else(parameter.Name) ?? parameter.Name;

            if (!string.IsNullOrEmpty(divChar))
            {
                divParameter = string.Format(CultureInfo.InvariantCulture, ", div='{0}'", divChar);
            }

            //TODO: This creates a very long line - break it up over multiple lines.
            return(string.Format(CultureInfo.InvariantCulture,
                                 "self._serialize.{0}(\"{1}\", {1}, '{2}'{3}{4}{5})",
                                 functionName,
                                 parameterName,
                                 parameter.ModelType.ToPythonRuntimeTypeString(),
                                 parameter.SkipUrlEncoding() ? ", skip_quote=True" : string.Empty,
                                 divParameter,
                                 BuildValidationParameters(parameter.Constraints)));
        }
 public override void ConstructModelMapper(TSBuilder builder)
 {
     builder.Text($"export const {Name}: msRest.CompositeMapper = ");
     ClientModelExtensions.ConstructMapper(builder, this, SerializedName, null, isPageable: true, expandComposite: true, isXML: CodeModel?.ShouldGenerateXmlSerialization == true);
     builder.Line(";");
 }
        public void GenerateOperationSpec(TSObject operationSpec)
        {
            operationSpec.QuotedStringProperty("httpMethod", HttpMethod.ToString().ToUpper());
            if (IsAbsoluteUrl)
            {
                operationSpec.QuotedStringProperty("baseUrl", CodeModelTS.BaseUrl);
            }

            string path = Path;

            if (!string.IsNullOrEmpty(path))
            {
                operationSpec.QuotedStringProperty("path", path);
            }

            Parameter[] logicalParameters = LogicalParameters.ToArray();

            AddParameterRefs(operationSpec, "urlParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Path));
            AddParameterRefs(operationSpec, "queryParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Query));
            AddParameterRefs(operationSpec, "headerParameters", logicalParameters.Where(p => p.Location == ParameterLocation.Header));

            bool addContentTypeProperty = (!string.IsNullOrEmpty(RequestContentType) && RequestContentType != CodeModelTS.RequestContentType);

            if (Body != null)
            {
                operationSpec.ObjectProperty("requestBody", requestBodyObject =>
                {
                    GenerateRequestParameterPath(requestBodyObject, Body, GetParameterTransformations());
                    requestBodyObject.Property("mapper", requestBodyMapper => ClientModelExtensions.ConstructRequestBodyMapper(requestBodyMapper, Body));
                });
            }
            else
            {
                IEnumerable <Parameter> formDataParameters = logicalParameters.Where(p => p.Location == ParameterLocation.FormData);
                if (formDataParameters.Any())
                {
                    AddParameterRefs(operationSpec, "formDataParameters", formDataParameters);
                    addContentTypeProperty = true;
                }
            }
            if (addContentTypeProperty)
            {
                operationSpec.QuotedStringProperty("contentType", RequestContentType);
            }

            operationSpec.ObjectProperty("responses", responses =>
            {
                bool isXml = CodeModelTS.ShouldGenerateXmlSerialization;
                foreach (KeyValuePair <HttpStatusCode, Response> statusCodeResponsePair in Responses)
                {
                    HttpStatusCode statusCode = statusCodeResponsePair.Key;
                    Response response         = statusCodeResponsePair.Value;

                    responses.ObjectProperty(((int)statusCode).ToString(), responseObject =>
                    {
                        if (response.Body != null)
                        {
                            responseObject.Property("bodyMapper", responseBodyMapper => ClientModelExtensions.ConstructResponseBodyMapper(responseBodyMapper, response, this));
                        }
                        if (response.Headers != null)
                        {
                            responseObject.Property("headersMapper", responseHeadersMapper => responseHeadersMapper.Text($"Mappers.{response.Headers.Name}"));
                        }
                    });
                }

                responses.ObjectProperty("default", defaultResponseObject =>
                {
                    Response defaultResponse = DefaultResponse;
                    if (defaultResponse != null && defaultResponse.Body != null)
                    {
                        defaultResponseObject.Property("bodyMapper", responseBodyMapper => ClientModelExtensions.ConstructResponseBodyMapper(responseBodyMapper, defaultResponse, this));
                    }
                });
            });


            if (CodeModel.ShouldGenerateXmlSerialization)
            {
                operationSpec.BooleanProperty("isXML", true);
            }

            operationSpec.TextProperty("serializer", "serializer");
        }