Ejemplo n.º 1
0
        /// <summary>
        ///		Obtiene una tabla con los métodos
        /// </summary>
        private void GetTableMethods(MLNode objMLRoot, DocumentFileModel objDocument)
        {
            LanguageStructModelCollection objColStructs = base.SelectItemsForGeneration(objDocument, LanguageStructModel.StructType.Method);

            if (objColStructs != null && objColStructs.Count > 0)
            {
                MLNode objMLTable;

                // Cabecera
                objMLRoot.Nodes.Add("br");
                objMLRoot.Nodes.Add("h3", "Métodos");
                // Cabecera de tabla
                objMLTable = MLBuilder.AddTable(objMLRoot, "Ambito", "Nombre", "Descripción");
                // Recorre los métodos
                foreach (LanguageStructModel objStruct in objColStructs)
                {
                    MethodModel objMethod = objStruct as MethodModel;

                    // Añade los datos del método
                    if (objMethod != null)
                    {                                                                                           // Cabecera
                        MLBuilder.AddRowTable(objMLTable, MLBuilderHelper.GetModifierText(objMethod.Modifier),
                                              objMethod.Name, objMethod.RemarksXml.Summary);
                        // Comentarios
                        AddRowRemarks(objMLTable, objMethod.RemarksXml.Remarks, 1, 2);
                        // Prototipo
                        AddRowRemarks(objMLTable, MLBuilderHelper.GetMethodPrototype(objMethod, objMethod.IsAsync, objMethod.ReturnType), 1, 2);
                        // Argumentos
                        if (objMethod.Arguments.Count > 0)
                        {
                            MLBuilder.AddRowNode(objMLTable, GetListArguments(objMethod), 1, 2);
                        }
                        // Valor devuelto
                        MLBuilder.AddRowNode(objMLTable, GetListReturnData(objMethod, objMethod.ReturnType), 1, 2);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private void ValidatePathParams(MethodModel method, string?path)
        {
            if (path == null)
            {
                path = string.Empty;
            }

            var pathParams = method.Parameters.Where(x => x.PathAttribute != null).ToList();

            // Check that there are no duplicate param names in the attributes
            var duplicateParams = pathParams.GroupBy(x => x.PathAttributeName !).Where(x => x.Count() > 1);

            foreach (var @params in duplicateParams)
            {
                this.diagnostics.ReportMultiplePathParametersForKey(method, @params.Key, @params);
            }

            // Check that each placeholder has a matching attribute, and vice versa
            // We allow a property param to fill in for a missing path param, but we allow them to duplicate
            // each other (the path param takes precedence), and allow a property param which doesn't have a placeholder.
            var placeholders = pathParamMatch.Matches(path).Cast <Match>().Select(x => x.Groups[1].Value).ToList();

            var missingParams = placeholders
                                .Except(pathParams.Select(x => x.PathAttributeName !).Concat(this.typeModel.Properties.Select(x => x.PathAttributeName !)));

            foreach (string missingParam in missingParams)
            {
                this.diagnostics.ReportMissingPathPropertyOrParameterForPlaceholder(method, missingParam);
            }

            var missingPlaceholders = pathParams.Select(x => x.PathAttributeName !).Except(placeholders);

            foreach (string missingPlaceholder in missingPlaceholders)
            {
                var parameters = pathParams.Where(x => x.PathAttributeName == missingPlaceholder);
                this.diagnostics.ReportMissingPlaceholderForPathParameter(method, missingPlaceholder, parameters);
            }
        }
Ejemplo n.º 3
0
        public void ComplexMethodOne()
        {
            var disposable = MethodModel.MethodThree();

            SerialDisposable.Disposable = disposable;

            // First Disposable
            DisposableTestContainer.Add(
                Subject
                .StartWith("TestString")
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(_ =>
            {
                // Second disposable; note the StartWith meaning the subject doesn't have to fire for this to be hit
                MethodOne();
                _intValue = MultiplyByTwo(73);
            },
                           exception => { },
                           () => _intValue = MultiplyByTwo(_intValue)));

            // Third disposable
            DisposableTestContainer.Add(disposable);
        }
Ejemplo n.º 4
0
        private MethodModel GetMethod(MethodInfo methodInfo)
        {
            var model = new MethodModel(methodInfo)
            {
                RequestAttribute              = Get <RequestAttributeBase>(),
                AllowAnyStatusCodeAttribute   = Get <AllowAnyStatusCodeAttribute>(),
                SerializationMethodsAttribute = Get <SerializationMethodsAttribute>(),
                IsDisposeMethod = methodInfo == MethodInfos.IDisposable_Dispose,
            };

            model.HeaderAttributes.AddRange(methodInfo.GetCustomAttributes <HeaderAttribute>()
                                            .Select(x => AttributeModel.Create(x, methodInfo)));

            model.Parameters.AddRange(methodInfo.GetParameters().Select(this.GetParameter));

            return(model);

            AttributeModel <T>?Get <T>() where T : Attribute
            {
                var attribute = methodInfo.GetCustomAttribute <T>();

                return(attribute == null ? null : AttributeModel.Create(attribute, methodInfo));
            }
        }
Ejemplo n.º 5
0
        protected virtual M GenerateMethod <M>(MethodModel model, M method) where M : BaseMethodDeclarationSyntax
        {
            method = GenerateMemberAttributes(model, method);

            foreach (var p in model.Parameters)
            {
                var parameter = _syntaxGenerator.ParameterDeclaration(p.Name, p.Type.Syntax) as ParameterSyntax;
                method = method.AddParameterListParameters(parameter) as M;
            }

            if (!model.IsAbstract)
            {
                if (model.Body != null)
                {
                    method = method.AddBodyStatements(model.Body.ToArray()) as M;
                }
            }
            else
            {
                method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) as M;
            }

            return(method);
        }
Ejemplo n.º 6
0
        public BaseMethodModel MapDown(MethodModel model, Type methodModelType)
        {
            object       methodModel              = Activator.CreateInstance(methodModelType);
            PropertyInfo nameProperty             = methodModelType.GetProperty("Name");
            PropertyInfo extensionProperty        = methodModelType.GetProperty("Extension");
            PropertyInfo genericArgumentsProperty = methodModelType.GetProperty("GenericArguments",
                                                                                BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            PropertyInfo modifiersProperty  = methodModelType.GetProperty("Modifiers");
            PropertyInfo parametersProperty = methodModelType.GetProperty("Parameters",
                                                                          BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            PropertyInfo returnTypeProperty = methodModelType.GetProperty("ReturnType",
                                                                          BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

            nameProperty?.SetValue(methodModel, model.Name);
            extensionProperty?.SetValue(methodModel, model.Extension);
            if (model.GenericArguments != null)
            {
                genericArgumentsProperty?.SetValue(methodModel,
                                                   HelperClass.ConvertList(genericArgumentsProperty.PropertyType.GetGenericArguments()[0],
                                                                           model.GenericArguments.Select(t => TypeModelMapper.EmitBaseType(t, genericArgumentsProperty.PropertyType.GetGenericArguments()[0])).ToList()));
            }
            modifiersProperty?.SetValue(methodModel, model.Modifiers);
            if (model.Parameters != null)
            {
                parametersProperty?.SetValue(methodModel,
                                             HelperClass.ConvertList(parametersProperty.PropertyType.GetGenericArguments()[0],
                                                                     model.Parameters.Select(p => new ParameterModelMapper().MapDown(p, parametersProperty.PropertyType.GetGenericArguments()[0])).ToList()));
            }
            if (model.ReturnType != null)
            {
                returnTypeProperty?.SetValue(methodModel,
                                             returnTypeProperty.PropertyType.Cast(TypeModelMapper.EmitBaseType(model.ReturnType, returnTypeProperty.PropertyType)));
            }

            return((BaseMethodModel)methodModel);
        }
        protected string GetMethodName(MethodModel methodModel)
        {
            var name = methodModel.Name.ToLower();

            switch (name)
            {
            case "get":
                return("getBy" + GetPascalCase(methodModel.Parameters.FirstOrDefault()?.Name));

            case "post":
                return("post" + GetPascalCase(methodModel.Parameters.FirstOrDefault()?.Name));

            case "put":
                var parameter = methodModel.Parameters.FirstOrDefault();
                if (methodModel.Parameters.Count > 1 && parameter?.Name.ToLower() == "id")
                {
                    parameter = methodModel.Parameters[1];
                }
                return("put" + GetPascalCase(parameter?.Name));

            default:
                return(GetCamelCase(methodModel.Name));
            }
        }
Ejemplo n.º 8
0
 public static MethodDbModel EmitUniqueType(MethodModel model)
 {
     return(UniqueEmitter.EmitType(model, propertyModel => new MethodDbModel(propertyModel)));
 }
        private static ApiDescription CreateApiDescription(
            RouteEndpoint routeEndpoint,
            MethodModel methodModel,
            HttpMethodAttribute httpMethodAttribute)
        {
            var apiDescription = new ApiDescription
            {
                HttpMethod       = httpMethodAttribute.Method,
                ActionDescriptor = new ActionDescriptor
                {
                    RouteValues = new Dictionary <string, string>
                    {
                        // Swagger uses this to group endpoints together.
                        // Group methods together using the service name.
                        ["controller"] = methodModel.MethodInfo.DeclaringType?.Name ?? string.Empty
                    }
                },
                RelativePath = routeEndpoint.RoutePattern.RawText?.TrimStart('/') ?? string.Empty
            };

            apiDescription.SupportedRequestFormats.Add(new ApiRequestFormat
            {
                MediaType = "application/json"
            });

            var responseTypes = methodModel.MethodInfo
                                .GetCustomAttributes(typeof(ProducesResponseTypeAttribute), false)
                                .OfType <ProducesResponseTypeAttribute>();

            var addDefaultResponseType = true;

            foreach (var responseType in responseTypes)
            {
                addDefaultResponseType = false;

                apiDescription.SupportedResponseTypes.Add(new ApiResponseType
                {
                    ApiResponseFormats = { new ApiResponseFormat {
                                               MediaType = "application/json"
                                           } },
                    ModelMetadata = responseType.Type == null ? null : new ExpressModelMetadata(responseType.Type),
                    StatusCode    = responseType.StatusCode,
                });
            }

            if (addDefaultResponseType)
            {
                apiDescription.SupportedResponseTypes.Add(new ApiResponseType
                {
                    ApiResponseFormats = { new ApiResponseFormat {
                                               MediaType = "application/json"
                                           } },
                    StatusCode = 200,
                });
            }

            foreach (var parameter in methodModel.Parameters)
            {
                apiDescription.ParameterDescriptions.Add(new ApiParameterDescription
                {
                    Name          = parameter.Name ?? "Input",
                    ModelMetadata = new ExpressModelMetadata(parameter.ParameterType),
                    Source        = parameter.GetBindingSource()
                });
            }

            return(apiDescription);
        }
Ejemplo n.º 10
0
        private void Generate(MethodModel method)
        {
            // [DebuggerStepThrough]
            WriteLine($"[{typeof(DebuggerStepThroughAttribute)}]");

            var methodStartIndex = _codeBuilder.Length + 4 * _indent;

            WriteLine($"public async {typeof(Task)} {method.UniqueName}({typeof(HttpContext)} httpContext)");
            WriteLine("{");
            Indent();
            var ctors = _model.HandlerType.GetConstructors();

            if (!method.MethodInfo.IsStatic)
            {
                if (ctors.Length > 1 || ctors[0].GetParameters().Length > 0)
                {
                    // Lazy, defer to DI system if
                    WriteLine($"var handler = ({S(_model.HandlerType)})_factory(httpContext.RequestServices, {typeof(Array)}.Empty<{typeof(object)}>());");
                }
                else
                {
                    WriteLine($"var handler = new {S(_model.HandlerType)}();");
                }
            }

            // Declare locals
            var hasAwait    = false;
            var hasFromBody = false;
            var hasFromForm = false;

            foreach (var parameter in method.Parameters)
            {
                var parameterName = "arg_" + parameter.Name.Replace("_", "__");
                if (parameter.ParameterType.Equals(typeof(HttpContext)))
                {
                    WriteLine($"var {parameterName} = httpContext;");
                }
                else if (parameter.ParameterType.Equals(typeof(IFormCollection)))
                {
                    WriteLine($"var {parameterName} = await httpContext.Request.ReadFormAsync();");
                    hasAwait = true;
                }
                else if (parameter.FromRoute != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromRoute, "httpContext.Request.RouteValues", nullable: true);
                }
                else if (parameter.FromQuery != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromQuery, "httpContext.Request.Query");
                }
                else if (parameter.FromHeader != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromHeader, "httpContext.Request.Headers");
                }
                else if (parameter.FromServices)
                {
                    WriteLine($"var {parameterName} = httpContext.RequestServices.GetRequiredService<{S(parameter.ParameterType)}>();");
                }
                else if (parameter.FromForm != null)
                {
                    if (!hasFromForm)
                    {
                        WriteLine($"var formCollection = await httpContext.Request.ReadFormAsync();");
                        hasAwait    = true;
                        hasFromForm = true;
                    }
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromForm, "formCollection");
                }
                else if (parameter.FromBody)
                {
                    if (!hasFromBody)
                    {
                        hasFromBody = true;
                    }

                    if (!parameter.ParameterType.Equals(typeof(JsonElement)))
                    {
                        FromBodyTypes.Add(parameter.ParameterType);
                    }

                    WriteLine($"var {parameterName} = await httpContext.Request.ReadFromJsonAsync<{S(parameter.ParameterType)}>();");
                    hasAwait = true;
                }
                else
                {
                    WriteLine($"{S(parameter.ParameterType)} {parameterName} = default;");
                }
            }

            AwaitableInfo awaitableInfo = default;

            // Populate locals
            if (method.MethodInfo.ReturnType.Equals(typeof(void)))
            {
                Write("");
            }
            else
            {
                if (AwaitableInfo.IsTypeAwaitable(method.MethodInfo.ReturnType, out awaitableInfo))
                {
                    if (awaitableInfo.ResultType.Equals(typeof(void)))
                    {
                        if (hasAwait)
                        {
                            Write("await ");
                        }
                        else
                        {
                            Write("return ");
                        }
                    }
                    else
                    {
                        Write("var result = await ");
                        hasAwait = true;
                    }
                }
                else
                {
                    Write("var result = ");
                }
            }
            WriteNoIndent($"{(method.MethodInfo.IsStatic ? S(_model.HandlerType) : "handler")}.{method.MethodInfo.Name}(");
            bool first = true;

            foreach (var parameter in method.Parameters)
            {
                var parameterName = "arg_" + parameter.Name.Replace("_", "__");
                if (!first)
                {
                    WriteNoIndent(", ");
                }
                WriteNoIndent(parameterName);
                first = false;
            }
            WriteLineNoIndent(");");

            if (!hasAwait)
            {
                // Remove " async" from method signature.
                _codeBuilder.Remove(methodStartIndex + 6, 6);
            }

            void AwaitOrReturn(string executeAsync)
            {
                if (hasAwait)
                {
                    Write("await ");
                }
                else
                {
                    Write("return ");
                }

                WriteLineNoIndent(executeAsync);
            }

            var unwrappedType = awaitableInfo.ResultType ?? method.MethodInfo.ReturnType;

            if (_metadataLoadContext.Resolve <IResult>().IsAssignableFrom(unwrappedType))
            {
                AwaitOrReturn("result.ExecuteAsync(httpContext);");
            }
            else if (unwrappedType.Equals(typeof(string)))
            {
                AwaitOrReturn($"httpContext.Response.WriteAsync(result);");
            }
            else if (!unwrappedType.Equals(typeof(void)))
            {
                AwaitOrReturn($"httpContext.Response.WriteAsJsonAsync(result);");
            }
            else if (!hasAwait && method.MethodInfo.ReturnType.Equals(typeof(void)))
            {
                // If awaitableInfo.ResultType is void, we've already returned the awaitable directly.
                WriteLine($"return {typeof(Task)}.CompletedTask;");
            }

            Unindent();
            WriteLine("}");
            WriteLine("");
        }
Ejemplo n.º 11
0
 public async Task <IActionResult> AddMethod([FromBody] MethodModel method)
 {
     logger.LogWarning($"POST: Methods: MethodName: {method.Name}");
     return(Json(await tests.SaveMethod(method)));
 }
Ejemplo n.º 12
0
        public void CanConstruct()
        {
            var instance = new MethodModel(_name, _parameters, _node, _model);

            Assert.That(instance, Is.Not.Null);
        }
        private void GenerateMethodParameters(MethodEmitter methodEmitter, MethodModel method, ResolvedSerializationMethods serializationMethods)
        {
            foreach (var parameter in method.Parameters)
            {
                var attributes = parameter.GetAllSetAttributes().ToList();

                if (parameter.IsByRef)
                {
                    this.diagnostics.ReportParameterMustNotBeByRef(method, parameter);
                }

                if (parameter.IsCancellationToken)
                {
                    if (attributes.Count > 0)
                    {
                        this.diagnostics.ReportCancellationTokenMustHaveZeroAttributes(method, parameter);
                    }

                    methodEmitter.EmitSetCancellationToken(parameter);
                }
                else
                {
                    if (attributes.Count > 1)
                    {
                        this.diagnostics.ReportParameterMustHaveZeroOrOneAttributes(method, parameter, attributes);
                    }

                    if (parameter.HeaderAttribute != null)
                    {
                        if (parameter.HeaderAttribute.Attribute.Value != null)
                        {
                            this.diagnostics.ReportHeaderParameterMustNotHaveValue(method, parameter);
                        }
                        if (parameter.HeaderAttribute.Attribute.Name.Contains(":"))
                        {
                            this.diagnostics.ReportHeaderParameterMustNotHaveColonInName(method, parameter);
                        }

                        methodEmitter.EmitAddHeaderParameter(parameter);
                    }
                    else if (parameter.PathAttribute != null)
                    {
                        methodEmitter.EmitAddPathParameter(
                            parameter,
                            serializationMethods.ResolvePath(parameter.PathAttribute.Attribute.SerializationMethod));
                    }
                    else if (parameter.QueryAttribute != null)
                    {
                        methodEmitter.EmitAddQueryParameter(
                            parameter,
                            serializationMethods.ResolveQuery(parameter.QueryAttribute.Attribute.SerializationMethod));
                    }
                    else if (parameter.HttpRequestMessagePropertyAttribute != null)
                    {
                        methodEmitter.EmitAddHttpRequestMessagePropertyParameter(parameter);
                    }
                    else if (parameter.RawQueryStringAttribute != null)
                    {
                        methodEmitter.EmitAddRawQueryStringParameter(parameter);
                    }
                    else if (parameter.QueryMapAttribute != null)
                    {
                        if (!methodEmitter.TryEmitAddQueryMapParameter(parameter, serializationMethods.ResolveQuery(parameter.QueryMapAttribute.Attribute.SerializationMethod)))
                        {
                            this.diagnostics.ReportQueryMapParameterIsNotADictionary(method, parameter);
                        }
                    }
                    else if (parameter.BodyAttribute != null)
                    {
                        methodEmitter.EmitSetBodyParameter(
                            parameter,
                            serializationMethods.ResolveBody(parameter.BodyAttribute.Attribute.SerializationMethod));
                    }
                    else
                    {
                        methodEmitter.EmitAddQueryParameter(parameter, serializationMethods.ResolveQuery(QuerySerializationMethod.Default));
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private void Generate(MethodModel method)
        {
            // [DebuggerStepThrough]
            WriteLine($"[{S(typeof(DebuggerStepThroughAttribute))}]");
            WriteLine($"public async {S(typeof(Task))} {method.MethodInfo.Name}({S(typeof(HttpContext))} httpContext)");
            WriteLine("{");
            Indent();
            var ctors = _model.HandlerType.GetConstructors();

            if (ctors.Length > 1 || ctors[0].GetParameters().Length > 0)
            {
                // Lazy, defer to DI system if
                WriteLine($"var handler = ({S(_model.HandlerType)})_factory(httpContext.RequestServices, {S(typeof(Array))}.Empty<{S(typeof(object))}>());");
            }
            else
            {
                WriteLine($"var handler = new {S(_model.HandlerType)}();");
            }

            // Declare locals
            var hasFromBody = false;
            var hasFromForm = false;

            foreach (var parameter in method.Parameters)
            {
                var parameterName = "arg_" + parameter.Name.Replace("_", "__");
                if (parameter.ParameterType.Equals(typeof(HttpContext)))
                {
                    WriteLine($"var {parameterName} = httpContext;");
                }
                else if (parameter.ParameterType.Equals(typeof(IFormCollection)))
                {
                    WriteLine($"var {parameterName} = await httpContext.Request.ReadFormAsync();");
                }
                else if (parameter.FromRoute != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromRoute, "httpContext.Request.RouteValues", nullable: true);
                }
                else if (parameter.FromQuery != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromQuery, "httpContext.Request.Query");
                }
                else if (parameter.FromHeader != null)
                {
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromHeader, "httpContext.Request.Headers");
                }
                else if (parameter.FromServices)
                {
                    WriteLine($"var {parameterName} = httpContext.RequestServices.GetRequiredService<{S(parameter.ParameterType)}>();");
                }
                else if (parameter.FromForm != null)
                {
                    if (!hasFromForm)
                    {
                        WriteLine($"var formCollection = await httpContext.Request.ReadFormAsync();");
                        hasFromForm = true;
                    }
                    GenerateConvert(parameterName, parameter.ParameterType, parameter.FromForm, "formCollection");
                }
                else if (parameter.FromBody)
                {
                    if (!hasFromBody)
                    {
                        WriteLine($"var reader = httpContext.RequestServices.GetService<{S(typeof(IHttpRequestReader))}>() ?? _requestReader;");
                        hasFromBody = true;
                    }

                    if (!parameter.ParameterType.Equals(typeof(JsonElement)))
                    {
                        FromBodyTypes.Add(parameter.ParameterType);
                    }

                    WriteLine($"var {parameterName} = ({S(parameter.ParameterType)})await reader.ReadAsync(httpContext, typeof({S(parameter.ParameterType)}));");
                }
            }

            AwaitableInfo awaitableInfo = default;

            // Populate locals
            if (method.MethodInfo.ReturnType.Equals(typeof(void)))
            {
                Write("");
            }
            else
            {
                if (AwaitableInfo.IsTypeAwaitable(method.MethodInfo.ReturnType, out awaitableInfo))
                {
                    if (awaitableInfo.ResultType.Equals(typeof(void)))
                    {
                        Write("await ");
                    }
                    else
                    {
                        Write("var result = await ");
                    }
                }
                else
                {
                    Write("var result = ");
                }
            }
            WriteNoIndent($"handler.{method.MethodInfo.Name}(");
            bool first = true;

            foreach (var parameter in method.Parameters)
            {
                var parameterName = "arg_" + parameter.Name.Replace("_", "__");
                if (!first)
                {
                    WriteNoIndent(", ");
                }
                WriteNoIndent(parameterName);
                first = false;
            }
            WriteLineNoIndent(");");
            var unwrappedType = awaitableInfo.ResultType ?? method.MethodInfo.ReturnType;

            if (_metadataLoadContext.Resolve <Result>().IsAssignableFrom(unwrappedType))
            {
                WriteLine("await result.ExecuteAsync(httpContext);");
            }
            else if (!unwrappedType.Equals(typeof(void)))
            {
                WriteLine($"await new {S(typeof(ObjectResult))}(result).ExecuteAsync(httpContext);");
            }
            Unindent();
            WriteLine("}");
            WriteLine("");
        }
Ejemplo n.º 15
0
    static void AddPartitionDefinition(OutputModel outputModel, DatabasePlan databasePlan, MethodModel methodModel, string name)
    {
        if (databasePlan.PartitionPlansByName.TryGetValue(name, out var partitionPlan))
        {
            if (!SymbolEqualityComparer.Default.Equals(partitionPlan.GetPkModel.MethodSymbol, methodModel.MethodSymbol))
            {
                outputModel.Report(Diagnostics.Errors.PartitionAlreadyDefined, methodModel.MethodSymbol);
            }
        }
        else
        {
            partitionPlan = new PartitionPlan
            {
                Name                        = name,
                PluralName                  = name.Pluralize(),
                ClassName                   = name.WithSuffix(Suffixes.Partition),
                BatchHandlersClassName      = name.WithSuffix(Suffixes.BatchHandlers),
                CreateOrReplaceClassName    = name.WithSuffix(Suffixes.CreateOrReplace),
                ReadClassName               = name.WithSuffix(Suffixes.Read),
                ReadOrThrowClassName        = name.WithSuffix(Suffixes.ReadOrThrow),
                ReadManyClassName           = name.WithSuffix(Suffixes.ReadMany),
                ReadUnionsClassName         = name.WithSuffix(Suffixes.ReadUnions),
                ReadOrThrowUnionsClassName  = name.WithSuffix(Suffixes.ReadOrThrowUnions),
                ReadManyUnionsClassName     = name.WithSuffix(Suffixes.ReadManyUnions),
                QueryBuilderClassName       = name.WithSuffix(Suffixes.QueryBuilder),
                QueryBuilderUnionsClassName = name.WithSuffix(Suffixes.QueryBuilderUnions),
                QueryClassName              = name.WithSuffix(Suffixes.Query),
                QueryUnionsClassName        = name.WithSuffix(Suffixes.QueryUnions),
                ReadOrCreateClassName       = name.WithSuffix(Suffixes.ReadOrCreate),
                CreateClassName             = name.WithSuffix(Suffixes.Create),
                BatchClassName              = name.WithSuffix(Suffixes.Batch),
                GetPkModel                  = methodModel
            };
            partitionPlan.BatchHandlersClassNameArgument = partitionPlan.BatchHandlersClassName.ToArgumentName();
            partitionPlan.ClassNameArgument             = partitionPlan.ClassName.ToArgumentName();
            databasePlan.PartitionPlansByName[name]     = partitionPlan;
            partitionPlan.QueryBuilderClassNameArgument = partitionPlan.QueryBuilderClassName.ToArgumentName();

            outputModel.ValidateNames(
                methodModel.MethodSymbol,
                partitionPlan.Name,
                partitionPlan.PluralName,
                partitionPlan.ClassName,
                partitionPlan.BatchHandlersClassName,
                partitionPlan.CreateOrReplaceClassName,
                partitionPlan.ReadClassName,
                partitionPlan.ReadOrThrowClassName,
                partitionPlan.ReadManyClassName,
                partitionPlan.QueryBuilderClassName,
                partitionPlan.QueryClassName,
                partitionPlan.ReadOrCreateClassName,
                partitionPlan.CreateClassName,
                partitionPlan.BatchClassName,
                partitionPlan.QueryBuilderUnionsClassName,
                partitionPlan.QueryUnionsClassName,
                partitionPlan.ReadManyUnionsClassName,
                partitionPlan.ReadOrThrowUnionsClassName,
                partitionPlan.ReadUnionsClassName);

            outputModel.ValidateIdentifiers(
                methodModel.MethodSymbol,
                partitionPlan.ClassNameArgument,
                partitionPlan.BatchHandlersClassNameArgument,
                partitionPlan.QueryBuilderClassNameArgument);
        }
    }
Ejemplo n.º 16
0
 public void ReportMissingPlaceholderForPathParameter(MethodModel _, string placeholder, IEnumerable <ParameterModel> parameters)
 {
     this.AddDiagnostic(missingPlaceholderForPathParameter, parameters.SelectMany(x => SymbolLocations(x.ParameterSymbol)), placeholder);
 }
Ejemplo n.º 17
0
 public void ReportMissingPathPropertyOrParameterForPlaceholder(MethodModel method, string placeholder)
 {
     // We'll put the squiggle on the attribute itself
     this.AddDiagnostic(missingPathPropertyOrParameterForPlaceholder, AttributeLocations(method.RequestAttribute, method.MethodSymbol), placeholder);
 }
Ejemplo n.º 18
0
 public void ReportMultiplePathParametersForKey(MethodModel _, string key, IEnumerable <ParameterModel> parameters)
 {
     this.AddDiagnostic(multiplePathParametersForKey, parameters.SelectMany(x => SymbolLocations(x.ParameterSymbol)), key);
 }
Ejemplo n.º 19
0
 public void ReportMethodMustHaveRequestAttribute(MethodModel method)
 {
     this.AddDiagnostic(methodMustHaveRequestAttribute, method.MethodSymbol.Locations);
 }
Ejemplo n.º 20
0
        /// <summary>
        ///		Obtiene el prototipo de un método Get o Set de una propiedad
        /// </summary>
        private string GetPropertyMethodPrototype(LanguageStructModel.ModifierType modifier, MethodModel method, string methodName)
        {
            string prototype = string.Empty;

            // Añade los datos al prototipo
            if (method != null)
            {
                // Añade el modificador (si es distinto al de la propiedad, es decir: public Property { private set }
                if (modifier != method.Modifier)
                {
                    prototype += GetModifierText(method.Modifier) + " ";
                }
                // Añade el nombre
                prototype = methodName + ";";
            }
            // Devuelve el prototipo
            return(prototype);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///		Convierte un método
        /// </summary>
        private StructDocumentationModel ConvertMethod(StructDocumentationModel parent, MethodModel item)
        {
            StructDocumentationModel structDoc = Create(parent, item, "Method");

            // Añade los argumentos
            structDoc.Parameters.Add(GetPrototype(item));
            AddListArguments(structDoc, item, item.Arguments);
            AddListTypeParameter(structDoc, item.TypeParameters);
            // Añade el valor de retorno
            structDoc.Childs.Add(GetReturnValue(structDoc, item.ReturnType, ConvertRemarks(item.RemarksXml.Returns)));
            // Devuelve la estructura
            return(structDoc);
        }
Ejemplo n.º 22
0
 public void AddMethod(MethodModel method)
 {
     Methods.Add(method);
 }
Ejemplo n.º 23
0
 static void Validate(OutputModel outputModel, ClassModel classModel, MethodModel model)
 {
 }
Ejemplo n.º 24
0
 public void ReportQueryMapParameterIsNotADictionary(MethodModel _, ParameterModel parameter)
 {
     this.AddDiagnostic(queryMapParameterIsNotADictionary, SymbolLocations(parameter.ParameterSymbol));
 }
        private void GenerateMethod(TypeEmitter typeEmitter, List <EmittedProperty> emittedProperties, MethodModel method)
        {
            var methodEmitter        = typeEmitter.EmitMethod(method);
            var serializationMethods = new ResolvedSerializationMethods(this.typeModel.SerializationMethodsAttribute?.Attribute, method.SerializationMethodsAttribute?.Attribute);

            if (method.RequestAttribute == null)
            {
                this.diagnostics.ReportMethodMustHaveRequestAttribute(method);
            }
            else
            {
                string?path = method.RequestAttribute.Attribute.Path;
                this.ValidatePathParams(method, path);
                this.ValidateCancellationTokenParams(method);
                this.ValidateMultipleBodyParams(method);
                this.ValidateHttpRequestMessageParams(method);

                methodEmitter.EmitRequestInfoCreation(method.RequestAttribute.Attribute);

                var resolvedAllowAnyStatusCode = method.AllowAnyStatusCodeAttribute ?? this.typeModel.TypeAllowAnyStatusCodeAttribute;
                if (resolvedAllowAnyStatusCode?.Attribute.AllowAnyStatusCode == true)
                {
                    methodEmitter.EmitSetAllowAnyStatusCode();
                }

                if (this.typeModel.BasePathAttribute?.Attribute.BasePath != null)
                {
                    methodEmitter.EmitSetBasePath(this.typeModel.BasePathAttribute.Attribute.BasePath);
                }

                this.GenerateMethodProperties(methodEmitter, emittedProperties, serializationMethods);

                foreach (var methodHeader in method.HeaderAttributes)
                {
                    if (methodHeader.Attribute.Name.Contains(":"))
                    {
                        this.diagnostics.ReportHeaderOnMethodMustNotHaveColonInName(method, methodHeader);
                    }

                    methodEmitter.EmitAddMethodHeader(methodHeader);
                }

                this.GenerateMethodParameters(methodEmitter, method, serializationMethods);

                if (!methodEmitter.TryEmitRequestMethodInvocation())
                {
                    this.diagnostics.ReportMethodMustHaveValidReturnType(method);
                }
            }
        }
Ejemplo n.º 26
0
 public void ReportMethodMustHaveValidReturnType(MethodModel method)
 {
     this.AddDiagnostic(methodMustHaveValidReturnType, method.MethodSymbol.Locations);
 }
Ejemplo n.º 27
0
 public void ReportParameterMustNotBeByRef(MethodModel _, ParameterModel parameter)
 {
     this.AddDiagnostic(parameterMustNotBeByRef, SymbolLocations(parameter.ParameterSymbol), parameter.Name);
 }
Ejemplo n.º 28
0
        private ICollection <MethodModel> GetMethods(Type type, TypeModel parent)
        {
            var list = new List <MethodModel>();

            // Used for ID generation
            var methodNames = new List <string>();

            // Get only methods for this object, none of the inherited methods.
            foreach (var methodInfo in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance))
            {
                try
                {
                    if (!methodInfo.IsSpecialName)
                    {
                        var method = new MethodModel
                        {
                            Parent      = parent,
                            ParentClass = parent.Id,
                            Name        = methodInfo.Name,
                        };

                        // Contains overloads - ID is the hashcode
                        if (methodNames.Contains(methodInfo.Name))
                        {
                            method.UseHashCodeForId = true;
                        }

                        methodNames.Add(methodInfo.Name);

                        if (methodInfo.IsGenericMethod)
                        {
                            var arguments = methodInfo.GetGenericArguments().Select(genericType => genericType.Name).ToList();

                            method.Name             = $"{methodInfo.Name}<{string.Join(",", arguments)}>";
                            method.UseHashCodeForId = true;
                        }

                        try
                        {
                            method.FullName           = methodInfo.ToString();
                            method.ReturnType         = GetTypeName(methodInfo.ReturnType);
                            method.ReturnTypeFullName = GetFullTypeName(methodInfo.ReturnType);

                            // Get common tags
                            var element =
                                xmlDocCommentReader.GetComments(methodInfo.IsGenericMethod ? methodInfo.GetGenericMethodDefinition() : methodInfo);
                            var comments = GetCommonTags(element);
                            method.Example    = comments.Example;
                            method.Remarks    = comments.Remarks;
                            method.Returns    = comments.Returns;
                            method.Summary    = comments.Summary;
                            method.Parameters = GetMethodParameters(methodInfo.GetParameters(), element); // Parameters
                        }
                        catch (Exception x)
                        {
                            method.LoadError = true;
                            method.FullName  = x.Message;
                        }

                        list.Add(method);
                    }
                }
                catch (Exception x)
                {
                    Trace.TraceError($"Type {type} : Parse methods Problem. {x.Message} => {x.Source}");
                }
            }

            return(list.OrderBy(x => x.Name).ToList());
        }
Ejemplo n.º 29
0
 public MethodTreeItem(MethodModel methodModel)
     : base(GetModifiers(methodModel) + methodModel.Name)
 {
     MethodModel = methodModel;
 }
Ejemplo n.º 30
0
 public void ReportMultipleBodyParameters(MethodModel _, IEnumerable <ParameterModel> parameters)
 {
     this.AddDiagnostic(multipleBodyParameters, parameters.SelectMany(x => SymbolLocations(x.ParameterSymbol)));
 }