Exemplo n.º 1
0
        protected override void WriteCommandBuilderBody(CodeMethod codeElement, RequestParams requestParams, bool isVoid, string returnType, LanguageWriter writer)
        {
            var parent       = codeElement.Parent as CodeClass;
            var classMethods = parent.Methods;
            var name         = codeElement.SimpleName;

            name = uppercaseRegex.Replace(name, "-$1").TrimStart('-').ToLower();

            if (codeElement.HttpMethod == null)
            {
                // Build method
                // Puts together the BuildXXCommand objects. Needs a nav property name e.g. users
                // Command("users") -> Command("get")
                if (string.IsNullOrWhiteSpace(name))
                {
                    // BuildCommand function
                    WriteUnnamedBuildCommand(codeElement, writer, parent, classMethods);
                }
                else
                {
                    WriteContainerCommand(codeElement, writer, parent, name);
                }
            }
            else
            {
                WriteExecutableCommand(codeElement, requestParams, writer, name);
            }
        }
Exemplo n.º 2
0
        public void OrdersWithMethodWithinClass()
        {
            var root      = CodeNamespace.InitRootNamespace();
            var comparer  = new CodeElementOrderComparer();
            var codeClass = new CodeClass {
                Name = "Class"
            };

            root.AddClass(codeClass);
            var method = new CodeMethod {
                Name = "Method"
            };

            codeClass.AddMethod(method);
            method.AddParameter(new CodeParameter {
                Name = "param"
            });
            var dataSet = new List <Tuple <CodeElement, CodeElement, int> > {
                new(null, null, 0),
                new(null, new CodeClass(), -1),
                new(new CodeClass(), null, 1),
                new(new CodeUsing(), new CodeProperty(), -1000),
                new(new CodeIndexer(), new CodeProperty(), 1000),
                new(method, new CodeProperty(), 1101),
                new(method, codeClass, -899)
            };
Exemplo n.º 3
0
    private static void AddPathQueryAndHeaderParameters(CodeMethod method)
    {
        var stringType = new CodeType {
            Name = "string",
        };

        method.AddPathQueryOrHeaderParameter(new CodeParameter {
            Name         = "q",
            Kind         = CodeParameterKind.QueryParameter,
            Type         = stringType,
            DefaultValue = "test",
            Description  = "The q option",
            Optional     = true
        });
        method.AddPathQueryOrHeaderParameter(new CodeParameter {
            Name = "test-path",
            Kind = CodeParameterKind.Path,
            Type = stringType
        });
        method.AddPathQueryOrHeaderParameter(new CodeParameter {
            Name        = "Test-Header",
            Kind        = CodeParameterKind.Headers,
            Type        = stringType,
            Description = "The test header",
        });
    }
        // GET: BillPropertyModels/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            BillPropertyModels billPropertyModels = db.BillProperties.Find(id);

            if (billPropertyModels == null)
            {
                return(HttpNotFound());
            }
            List <CodeMethod>     list = CodeMethod.GetCodeMethod();
            List <SelectListItem> item = list.Select(c => new SelectListItem
            {
                Value = c.Id,
                Text  = c.Description
            }).ToList();

            foreach (var tmp in item)
            {
                if (billPropertyModels.CodeMethod == tmp.Text)
                {
                    tmp.Selected = true;
                    break;
                }
            }
            ViewBag.List = item;
            return(View(billPropertyModels));
        }
Exemplo n.º 5
0
 public static void AddAccessedProperty(this CodeMethod codeMethod)
 {
     codeMethod.AccessedProperty = new CodeProperty {
         Name = "someProperty"
     };
     (codeMethod.Parent as CodeClass)?.AddProperty(codeMethod.AccessedProperty);
 }
Exemplo n.º 6
0
    public void WritesExecutableCommandForGetRequestModel()
    {
        method.Kind        = CodeMethodKind.CommandBuilder;
        method.Description = "Test description";
        method.SimpleName  = "User";
        method.HttpMethod  = HttpMethod.Get;
        var userClass = root.AddClass(new CodeClass
        {
            Name = "User",
            Kind = CodeClassKind.Model
        }).First();
        var stringType = new CodeType
        {
            Name           = "user",
            TypeDefinition = userClass,
        };
        var generatorMethod = new CodeMethod
        {
            Kind       = CodeMethodKind.RequestGenerator,
            Name       = "CreateGetRequestInformation",
            HttpMethod = method.HttpMethod
        };

        method.OriginalMethod = new CodeMethod
        {
            Kind       = CodeMethodKind.RequestExecutor,
            HttpMethod = method.HttpMethod,
            ReturnType = stringType,
            Parent     = method.Parent
        };
        var codeClass = method.Parent as CodeClass;

        codeClass.AddMethod(generatorMethod);

        AddRequestProperties();
        AddRequestBodyParameters(method.OriginalMethod);
        AddPathQueryAndHeaderParameters(generatorMethod);

        writer.Write(method);
        var result = tw.ToString();

        Assert.Contains("var command = new Command(\"user\");", result);
        Assert.Contains("command.Description = \"Test description\";", result);
        Assert.Contains("var qOption = new Option<string>(\"-q\", getDefaultValue: ()=> \"test\", description: \"The q option\")", result);
        Assert.Contains("qOption.IsRequired = false;", result);
        Assert.Contains("var jsonNoIndentOption = new Option<bool>(\"--json-no-indent\", r => {", result);
        Assert.Contains("command.AddOption(qOption);", result);
        Assert.Contains("command.AddOption(jsonNoIndentOption);", result);
        Assert.Contains("command.AddOption(outputOption);", result);
        Assert.Contains("command.SetHandler(async (invocationContext) => {", result);
        Assert.Contains("var q = invocationContext.ParseResult.GetValueForOption(qOption);", result);
        Assert.Contains("var requestInfo = CreateGetRequestInformation", result);
        Assert.Contains("requestInfo.PathParameters.Add(\"test%2Dpath\", testPath);", result);
        Assert.Contains("var response = await RequestAdapter.SendPrimitiveAsync<Stream>(requestInfo, errorMapping: default, cancellationToken: cancellationToken);", result);
        Assert.Contains("var formatterOptions = output.GetOutputFormatterOptions(new FormatterOptionsModel(!jsonNoIndent));", result);
        Assert.Contains("response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken)", result);
        Assert.Contains("await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken);", result);
        Assert.Contains("});", result);
        Assert.Contains("return command;", result);
    }
Exemplo n.º 7
0
        private string GetNativeCallMehtodBody(CodeMethod caller, CodeField field, CodeType typeDecl)
        {
            var sb = new StringBuilder();

            sb.Append("fixed (").Append(typeDecl.Name).Append("* self = &this)\n{\n\t");
            if (caller.RetVal.Type != "void")
            {
                sb.Append("return ");
            }

            var argTypes = new List <string>();

            if (caller.HasThisArg)
            {
                argTypes.Add(typeDecl.Name + "*");
            }
            argTypes.AddRange(caller.Parameters.Select(arg => CSharpCodeGen.GetClrTypeName(arg.Type)));
            argTypes.Add(CSharpCodeGen.GetClrTypeName(caller.RetVal.Type));

            sb.Append("((delegate* unmanaged[Stdcall]<").Append(string.Join(", ", argTypes)).Append(">)");
            sb.Append(field.Name).Append(")(");
            var args = new List <string>();

            if (caller.HasThisArg)
            {
                args.Add("self");
            }
            args.AddRange(caller.Parameters.Select(arg => arg.Name));
            sb.Append(string.Join(", ", args));
            sb.Append(");");
            sb.Append("\n}");

            return(sb.ToString());
        }
Exemplo n.º 8
0
        public void WriteGetterAdditionalData()
        {
            var getter = new CodeMethod()
            {
                Name        = "getAdditionalData",
                Description = "This method gets the emailAddress",
                ReturnType  = new CodeType()
                {
                    Name       = "additionalData",
                    IsNullable = false
                },
                Kind             = CodeMethodKind.Getter,
                AccessedProperty = new CodeProperty()
                {
                    Name   = "additionalData",
                    Access = AccessModifier.Private,
                    Kind   = CodePropertyKind.AdditionalData,
                    Type   = new CodeType
                    {
                        Name = "additionalData"
                    }
                },
                Parent = parentClass
            };

            _codeMethodWriter.WriteCodeElement(getter, languageWriter);
            var result = stringWriter.ToString();

            Assert.Contains("public function getAdditionalData(): array", result);
            Assert.Contains("return $this->additionalData;", result);
        }
Exemplo n.º 9
0
        public void WriteRequestBuilderWithParametersBody()
        {
            var codeMethod = new CodeMethod()
            {
                ReturnType = new CodeType()
                {
                    Name       = "MessageRequestBuilder",
                    IsNullable = false
                },
                Name   = "messageById",
                Parent = parentClass,
                Kind   = CodeMethodKind.RequestBuilderWithParameters
            };

            codeMethod.AddParameter(new CodeParameter
            {
                Kind = CodeParameterKind.Path,
                Name = "id",
                Type = new CodeType
                {
                    Name = "string"
                }
            });

            _codeMethodWriter.WriteCodeElement(codeMethod, languageWriter);
            var result = stringWriter.ToString();

            Assert.Contains("function messageById(string $id): MessageRequestBuilder {", result);
            Assert.Contains("return new MessageRequestBuilder($this->pathParameters, $this->requestAdapter, $id);", result);
        }
Exemplo n.º 10
0
        public void WriteConstructorBody()
        {
            var constructor = new CodeMethod()
            {
                Name        = "constructor",
                Access      = AccessModifier.Public,
                Description = "The constructor for this class",
                ReturnType  = new CodeType()
                {
                    Name = "void"
                },
                Kind = CodeMethodKind.Constructor
            };

            parentClass.AddMethod(constructor);

            var propWithDefaultValue = new CodeProperty()
            {
                Name         = "type",
                DefaultValue = "\"#microsoft.graph.entity\"",
                Kind         = CodePropertyKind.Custom
            };

            parentClass.AddProperty(propWithDefaultValue);

            _codeMethodWriter.WriteCodeElement(constructor, languageWriter);
            var result = stringWriter.ToString();

            Assert.Contains("public function __construct", result);
            Assert.Contains("$this->setType('#microsoft.graph.entity')", result);
        }
Exemplo n.º 11
0
        public void WriteDeserializer(CodeProperty property, string expected)
        {
            parentClass.Kind = CodeClassKind.Model;
            var deserializerMethod = new CodeMethod()
            {
                Name        = "getDeserializationFields",
                Kind        = CodeMethodKind.Deserializer,
                Description = "Just some random method",
                ReturnType  = new CodeType
                {
                    IsNullable     = false,
                    CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array,
                    Name           = "array"
                }
            };

            parentClass.AddMethod(deserializerMethod);
            parentClass.AddProperty(property);
            _refiner.Refine(parentClass.Parent as CodeNamespace);
            languageWriter.Write(deserializerMethod);
            if (property.ExistsInBaseType)
            {
                Assert.DoesNotContain(expected, stringWriter.ToString());
            }
            else
            {
                Assert.Contains(expected, stringWriter.ToString());
            }
        }
Exemplo n.º 12
0
 public CodeMethodWriterTests()
 {
     languageWriter = LanguageWriter.GetLanguageWriter(GenerationLanguage.PHP, DefaultPath, DefaultName);
     stringWriter   = new StringWriter();
     languageWriter.SetTextWriter(stringWriter);
     root              = CodeNamespace.InitRootNamespace();
     root.Name         = "Microsoft\\Graph";
     _codeMethodWriter = new CodeMethodWriter(new PhpConventionService());
     parentClass       = new CodeClass()
     {
         Name = "parentClass"
     };
     root.AddClass(parentClass);
     method = new CodeMethod()
     {
         Name        = MethodName,
         IsAsync     = true,
         Description = "This is a very good method to try all the good things"
     };
     method.ReturnType = new CodeType()
     {
         Name = ReturnTypeName
     };
     _refiner = new PhpRefiner(new GenerationConfiguration {
         Language = GenerationLanguage.PHP
     });
     parentClass.AddMethod(method);
 }
Exemplo n.º 13
0
 public CodeMethodWriterTests()
 {
     writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Ruby, DefaultPath, DefaultName);
     tw     = new StringWriter();
     writer.SetTextWriter(tw);
     root        = CodeNamespace.InitRootNamespace();
     parentClass = new CodeClass {
         Name = "parentClass"
     };
     root.AddClass(parentClass);
     method = new CodeMethod {
         Name = MethodName,
     };
     method.ReturnType = new CodeType {
         Name = ReturnTypeName
     };
     voidMethod = new CodeMethod {
         Name = MethodName,
     };
     voidMethod.ReturnType = new CodeType {
         Name = "void"
     };
     parentClass.AddMethod(voidMethod);
     parentClass.AddMethod(method);
 }
Exemplo n.º 14
0
        public void WriteDeserializerMergeWhenHasParent()
        {
            var currentClass = parentClass;

            currentClass.Kind = CodeClassKind.Model;
            var declaration = currentClass.StartBlock as ClassDeclaration;

            declaration.Inherits = new CodeType()
            {
                Name = "Entity", IsExternal = true, IsNullable = false
            };
            currentClass.AddProperty(
                new CodeProperty()
            {
                Name   = "name",
                Access = AccessModifier.Private,
                Kind   = CodePropertyKind.Custom,
                Type   = new CodeType()
                {
                    Name = "string"
                }
            }
                );
            var deserializerMethod = new CodeMethod()
            {
                Name        = "getDeserializationFields",
                Kind        = CodeMethodKind.Deserializer,
                Description = "Just some random method",
                ReturnType  = new CodeType()
                {
                    IsNullable     = false,
                    CollectionKind = CodeTypeBase.CodeTypeCollectionKind.Array,
                    Name           = "array"
                }
            };
            var cls = new CodeClass()
            {
                Name       = "ModelParent",
                Kind       = CodeClassKind.Model,
                Parent     = root,
                StartBlock = new ClassDeclaration()
                {
                    Implements = { }, Name = "ModelParent", Parent = root
                }
            };

            root.AddClass(cls);
            currentClass.StartBlock.Inherits = new CodeType()
            {
                TypeDefinition = cls
            };
            currentClass.AddMethod(deserializerMethod);

            _refiner.Refine(parentClass.Parent as CodeNamespace);
            _codeMethodWriter.WriteCodeElement(deserializerMethod, languageWriter);
            var result = stringWriter.ToString();

            Assert.Contains("array_merge(parent::getFieldDeserializers()", result);
        }
Exemplo n.º 15
0
    public void WritesExecutableCommandForPostRequestWithStreamBody()
    {
        method.Kind       = CodeMethodKind.CommandBuilder;
        method.SimpleName = "User";
        method.HttpMethod = HttpMethod.Post;
        var stringType = new CodeType
        {
            Name = "string",
        };
        var bodyType = new CodeType
        {
            Name = "stream"
        };
        var generatorMethod = new CodeMethod
        {
            Kind       = CodeMethodKind.RequestGenerator,
            Name       = "CreatePostRequestInformation",
            HttpMethod = method.HttpMethod
        };

        method.OriginalMethod = new CodeMethod
        {
            Kind       = CodeMethodKind.RequestExecutor,
            HttpMethod = method.HttpMethod,
            ReturnType = stringType,
            Parent     = method.Parent
        };
        method.OriginalMethod.AddParameter(new CodeParameter
        {
            Name = "body",
            Kind = CodeParameterKind.RequestBody,
            Type = bodyType,
        });
        var codeClass = method.Parent as CodeClass;

        codeClass.AddMethod(generatorMethod);

        AddRequestProperties();
        AddPathQueryAndHeaderParameters(generatorMethod);

        writer.Write(method);
        var result = tw.ToString();

        Assert.Contains("var command = new Command(\"user\");", result);
        Assert.Contains("var qOption = new Option<string>(\"-q\", getDefaultValue: ()=> \"test\", description: \"The q option\")", result);
        Assert.Contains("qOption.IsRequired = false;", result);
        Assert.Contains("command.AddOption(qOption);", result);
        Assert.Contains("var fileOption = new Option<FileInfo>(\"--file\")", result);
        Assert.Contains("fileOption.IsRequired = true;", result);
        Assert.Contains("command.AddOption(fileOption);", result);
        Assert.Contains("var file = invocationContext.ParseResult.GetValueForOption(fileOption);", result);
        Assert.Contains("using var stream = file.OpenRead();", result);
        Assert.Contains("var requestInfo = CreatePostRequestInformation", result);
        Assert.Contains("requestInfo.PathParameters.Add(\"test%2Dpath\", testPath);", result);
        Assert.Contains("var response = await RequestAdapter.SendPrimitiveAsync<Stream>(requestInfo, errorMapping: default, cancellationToken: cancellationToken);", result);
        Assert.Contains("return command;", result);
    }
Exemplo n.º 16
0
        public ActionResult Edit(BillPropertyModels billPropertyModels)
        {
            if (ModelState.IsValid)
            {
                switch (billPropertyModels.CodeMethod)
                {
                case CodeMethod.Month:
                    billPropertyModels.Year         = 2;
                    billPropertyModels.Month        = 2;
                    billPropertyModels.Day          = 0;
                    billPropertyModels.SerialNumber = 6;
                    break;

                case CodeMethod.Serial:
                    billPropertyModels.Year         = 0;
                    billPropertyModels.Month        = 0;
                    billPropertyModels.Day          = 0;
                    billPropertyModels.SerialNumber = this.GetSerialNumbers(billPropertyModels.Code);
                    break;

                case CodeMethod.Manual:
                    billPropertyModels.Year         = 0;
                    billPropertyModels.Month        = 0;
                    billPropertyModels.Day          = 0;
                    billPropertyModels.SerialNumber = 0;
                    break;

                default:
                    billPropertyModels.Year         = 2;
                    billPropertyModels.Month        = 2;
                    billPropertyModels.Day          = 2;
                    billPropertyModels.SerialNumber = 4;
                    break;
                }
                db.Entry(billPropertyModels).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            List <CodeMethod>     list = CodeMethod.GetBillType();
            List <SelectListItem> item = list.Select(c => new SelectListItem
            {
                Value = c.Id,
                Text  = c.Description
            }).ToList();

            foreach (var tmp in item)
            {
                if (billPropertyModels.CodeMethod == tmp.Text)
                {
                    tmp.Selected = true;
                    break;
                }
            }
            ViewBag.List = item;
            return(View(billPropertyModels));
        }
Exemplo n.º 17
0
        static void GenerateEndMethodImpl(CodeClass c, MethodInfo endProcessMethod, string name, MethodInfo mi)
        {
            CodeMethod  m = c.ImplementMethod(mi);
            CodeBuilder b = m.CodeBuilder;

            ParameterInfo [] pinfos = mi.GetParameters();

            ParameterInfo         p = pinfos [0];
            CodeArgumentReference asyncResultRef = m.GetArg(0);

            CodeVariableDeclaration paramsDecl = new CodeVariableDeclaration(typeof(object []), "parameters");

            b.CurrentBlock.Add(paramsDecl);
            CodeVariableReference paramsRef = paramsDecl.Variable;

            b.Assign(paramsRef,
                     new CodeNewArray(typeof(object), new CodeLiteral(pinfos.Length - 1)));

            /*
             * for (int i = 0; i < pinfos.Length - 2; i++) {
             *      ParameterInfo par = pinfos [i];
             *      if (!par.IsOut)
             *              b.Assign (
             *                      new CodeArrayItem (paramsRef, new CodeLiteral (i)),
             *                      new CodeCast (typeof (object),
             *                              new CodeArgumentReference (par.ParameterType, par.Position + 1, "arg" + i)));
             * }
             */
#if USE_OD_REFERENCE_IN_PROXY
            CodePropertyReference argMethodInfo = GetOperationMethod(m, b, name, "EndMethod");
#else
            CodeMethodCall argMethodInfo = new CodeMethodCall(typeof(MethodBase), "GetCurrentMethod");
#endif
            CodeLiteral argOperName = new CodeLiteral(name);

            CodeVariableReference retValue = null;
            if (mi.ReturnType == typeof(void))
            {
                b.Call(m.GetThis(), endProcessMethod, argMethodInfo, argOperName, paramsRef, asyncResultRef);
            }
            else
            {
                CodeVariableDeclaration retValueDecl = new CodeVariableDeclaration(mi.ReturnType, "retValue");
                b.CurrentBlock.Add(retValueDecl);
                retValue = retValueDecl.Variable;
                b.Assign(retValue,
                         new CodeCast(mi.ReturnType,
                                      b.CallFunc(m.GetThis(), endProcessMethod, argMethodInfo, argOperName, paramsRef, asyncResultRef)));
            }
            // FIXME: fill out parameters
            if (retValue != null)
            {
                b.Return(retValue);
            }
        }
Exemplo n.º 18
0
        public void Defensive()
        {
            var root   = CodeNamespace.InitRootNamespace();
            var method = new CodeMethod(root)
            {
                Name = "class",
            };

            Assert.False(method.IsOfKind((CodeMethodKind[])null));
            Assert.False(method.IsOfKind(new CodeMethodKind[] { }));
        }
Exemplo n.º 19
0
        public void IsOfKind()
        {
            var method = new CodeMethod {
                Name = "class",
            };

            Assert.False(method.IsOfKind(CodeMethodKind.Constructor));
            method.Kind = CodeMethodKind.Deserializer;
            Assert.True(method.IsOfKind(CodeMethodKind.Deserializer));
            Assert.True(method.IsOfKind(CodeMethodKind.Deserializer, CodeMethodKind.Getter));
            Assert.False(method.IsOfKind(CodeMethodKind.Getter));
        }
Exemplo n.º 20
0
    public void WritesExecutableCommandForPostVoidRequest()
    {
        method.Kind       = CodeMethodKind.CommandBuilder;
        method.SimpleName = "User";
        method.HttpMethod = HttpMethod.Post;
        var stringType = new CodeType {
            Name = "string",
        };
        var voidType = new CodeType {
            Name = "void",
        };
        var generatorMethod = new CodeMethod {
            Kind       = CodeMethodKind.RequestGenerator,
            Name       = "CreatePostRequestInformation",
            HttpMethod = method.HttpMethod
        };

        method.OriginalMethod = new CodeMethod {
            Kind       = CodeMethodKind.RequestExecutor,
            HttpMethod = method.HttpMethod,
            ReturnType = voidType,
            Parent     = method.Parent
        };
        method.OriginalMethod.AddParameter(new CodeParameter {
            Name = "body",
            Kind = CodeParameterKind.RequestBody,
            Type = stringType,
        });
        var codeClass = method.Parent as CodeClass;

        codeClass.AddMethod(generatorMethod);

        AddRequestProperties();
        AddPathQueryAndHeaderParameters(generatorMethod);

        writer.Write(method);
        var result = tw.ToString();

        Assert.Contains("var command = new Command(\"user\");", result);
        Assert.Contains("var qOption = new Option<string>(\"-q\", getDefaultValue: ()=> \"test\", description: \"The q option\")", result);
        Assert.Contains("qOption.IsRequired = false;", result);
        Assert.Contains("command.AddOption(qOption);", result);
        Assert.Contains("var bodyOption = new Option<string>(\"--body\")", result);
        Assert.Contains("bodyOption.IsRequired = true;", result);
        Assert.Contains("command.AddOption(bodyOption);", result);
        Assert.Contains("var requestInfo = CreatePostRequestInformation", result);
        Assert.Contains("requestInfo.PathParameters.Add(\"test%2Dpath\", testPath);", result);
        Assert.Contains("await RequestAdapter.SendNoContentAsync(requestInfo, errorMapping: default, cancellationToken: cancellationToken);", result);
        Assert.Contains("Console.WriteLine(\"Success\");", result);
        Assert.Contains("return command;", result);
        Assert.DoesNotContain("response = await outputFilter?.FilterOutputAsync(response, query, cancellationToken)", result);
        Assert.DoesNotContain("await formatter.WriteOutputAsync(response, formatterOptions, cancellationToken);", result);
    }
        // GET: BillPropertyModels/Create
        public ActionResult Create()
        {
            List <CodeMethod>     list = CodeMethod.GetCodeMethod();
            List <SelectListItem> item = list.Select(c => new SelectListItem
            {
                Value = c.Id,
                Text  = c.Description
            }).ToList();

            ViewBag.List = item;
            return(View());
        }
Exemplo n.º 22
0
    private void AddRequestBodyParameters(CodeMethod target = default, bool useComplexTypeForBody = false)
    {
        var stringType = new CodeType {
            Name = "string",
        };

        target ??= method;
        var requestConfigClass = (target.Parent as CodeClass).AddInnerClass(new CodeClass {
            Name = "RequestConfig",
            Kind = CodeClassKind.RequestConfiguration,
        }).First();

        requestConfigClass.AddProperty(new() {
            Name = "h",
            Kind = CodePropertyKind.Headers,
            Type = stringType,
        },
                                       new () {
            Name = "q",
            Kind = CodePropertyKind.QueryParameters,
            Type = stringType,
        },
                                       new () {
            Name = "o",
            Kind = CodePropertyKind.Options,
            Type = stringType,
        });
        target.AddParameter(new CodeParameter {
            Name = "c",
            Kind = CodeParameterKind.RequestConfiguration,
            Type = new CodeType {
                Name           = "RequestConfig",
                TypeDefinition = requestConfigClass,
            },
            Optional = true,
        });
        target.AddParameter(new CodeParameter {
            Name = "b",
            Kind = CodeParameterKind.RequestBody,
            Type = useComplexTypeForBody ? new CodeType {
                Name           = "SomeComplexTypeForRequestBody",
                TypeDefinition = root.AddClass(new CodeClass {
                    Name = "SomeComplexTypeForRequestBody",
                    Kind = CodeClassKind.Model,
                }).First(),
            } : stringType,
        });
        target.AddParameter(new CodeParameter {
            Name = "r",
            Kind = CodeParameterKind.ResponseHandler,
            Type = stringType,
        });
    }
Exemplo n.º 23
0
        public void ParametersExtensionsReturnsValue()
        {
            var method = new CodeMethod {
                Name = "method1"
            };

            method.AddParameter(new CodeParameter {
                Name = "param1",
                Kind = CodeParameterKind.Custom,
            });
            Assert.NotNull(method.Parameters.OfKind(CodeParameterKind.Custom));
            Assert.Null(method.Parameters.OfKind(CodeParameterKind.RequestBody));
        }
Exemplo n.º 24
0
    public void Defensive()
    {
        var method = new CodeMethod {
            Name = "class",
        };

        Assert.Throws <ArgumentNullException>(() => new CodeFunction(null));
        Assert.Throws <InvalidOperationException>(() => new CodeFunction(method));
        method.IsStatic = true;
        var function = new CodeFunction(method);

        Assert.Equal(method, function.OriginalLocalMethod);
    }
Exemplo n.º 25
0
 public CodeFunction(CodeMethod method)
 {
     if (method == null)
     {
         throw new ArgumentNullException(nameof(method));
     }
     if (!method.IsStatic)
     {
         throw new InvalidOperationException("The original method must be static");
     }
     EnsureElementsAreChildren(method);
     OriginalLocalMethod = method;
 }
Exemplo n.º 26
0
        // GET: BillPropertyModels/Create
        public ActionResult Create()
        {
            List <CodeMethod>     list = CodeMethod.GetBillType();
            List <SelectListItem> item = list.Select(c => new SelectListItem
            {
                Value = c.Id,
                Text  = c.Description
            }).ToList();

            ViewBag.List         = item;
            ViewBag.BillSortList = BillSortMethod.GetBillSortMethod(base.ConnectionString);
            return(View());
        }
Exemplo n.º 27
0
        public void IsOfKind()
        {
            var root   = CodeNamespace.InitRootNamespace();
            var method = new CodeMethod(root)
            {
                Name = "class",
            };

            Assert.False(method.IsOfKind(CodeMethodKind.Constructor));
            method.MethodKind = CodeMethodKind.Deserializer;
            Assert.True(method.IsOfKind(CodeMethodKind.Deserializer));
            Assert.True(method.IsOfKind(CodeMethodKind.Deserializer, CodeMethodKind.Getter));
            Assert.False(method.IsOfKind(CodeMethodKind.Getter));
        }
Exemplo n.º 28
0
        private void GenerateMethodCode(CodeMethod methodDecl)
        {
            foreach (CodeComment commentDecl in methodDecl.Comments)
            {
                GenerateCommentCode(commentDecl);
            }

            WriteCustomAttributes(methodDecl.CustomAttributes);
            WriteAttributes(methodDecl.Attributes);
            Output.Write(GetClrTypeName(methodDecl.RetVal.Type));
            Output.Write(" ");
            Output.Write(methodDecl.Name);
            Output.Write("(");

            var args = new List <string>(methodDecl.Parameters.Count);

            foreach (CodeMethodParameter param in methodDecl.Parameters)
            {
                string modifier = string.Empty;
                if (param.Direction == CodeMethodParameterDirection.Ref)
                {
                    modifier = "ref ";
                }
                else if (param.Direction == CodeMethodParameterDirection.Out)
                {
                    modifier = "out ";
                }
                string customAttributes = string.Join(", ", param.CustomAttributes.Select(a => a.ToString()));
                if (customAttributes != null && customAttributes.Length > 0)
                {
                    customAttributes = "[" + customAttributes + "]";
                }

                args.Add(string.Format("{3}{0}{1} {2}", modifier, GetClrTypeName(param.Type), param.Name, customAttributes));
            }
            Output.Write(string.Join(", ", args));
            //Output.Write(string.Join(", ", methodDecl.Parameters.Select(arg => GetClrTypeName(arg.Type) + " " + arg.Name)));


            Output.Write(")");
            if (methodDecl.NoBody)
            {
                Output.WriteLine(";");
                return;
            }
            WriteBlockStart(CodeGenBlockType.Method);
            GenerateMethodBodyCode(methodDecl.Body);
            WriteBlockEnd(CodeGenBlockType.Method);
        }
Exemplo n.º 29
0
        static void GenerateBeginMethodImpl(CodeClass c, MethodInfo beginProcessMethod, string name, MethodInfo mi)
        {
            CodeMethod  m = c.ImplementMethod(mi);
            CodeBuilder b = m.CodeBuilder;

            // object [] parameters = new object [x];
            // parameters [0] = arg1;
            // parameters [1] = arg2;
            // ...
            // (return) BeginProcess (Contract.Operations [operName].BeginMethod, operName, parameters, asyncCallback, userState);
            ParameterInfo []        pinfos     = mi.GetParameters();
            CodeVariableDeclaration paramsDecl = new CodeVariableDeclaration(typeof(object []), "parameters");

            b.CurrentBlock.Add(paramsDecl);
            CodeVariableReference paramsRef = paramsDecl.Variable;

            b.Assign(paramsRef,
                     new CodeNewArray(typeof(object), new CodeLiteral(pinfos.Length - 2)));
            for (int i = 0; i < pinfos.Length - 2; i++)
            {
                ParameterInfo par = pinfos [i];
                if (!par.IsOut)
                {
                    b.Assign(
                        new CodeArrayItem(paramsRef, new CodeLiteral(i)),
                        new CodeCast(typeof(object), m.GetArg(i)));
                }
            }
#if USE_OD_REFERENCE_IN_PROXY
            CodePropertyReference argMethodInfo = GetOperationMethod(m, b, name, "BeginMethod");
#else
            CodeMethodCall argMethodInfo = new CodeMethodCall(typeof(MethodBase), "GetCurrentMethod");
#endif
            CodeLiteral argOperName = new CodeLiteral(name);

            ParameterInfo         p           = pinfos [pinfos.Length - 2];
            CodeArgumentReference callbackRef = new CodeArgumentReference(typeof(AsyncCallback), p.Position + 1, p.Name);
            p = pinfos [pinfos.Length - 1];
            CodeArgumentReference stateRef = new CodeArgumentReference(typeof(object), p.Position + 1, p.Name);

            CodeVariableDeclaration retValueDecl = new CodeVariableDeclaration(mi.ReturnType, "retValue");
            b.CurrentBlock.Add(retValueDecl);
            CodeVariableReference retValue = retValueDecl.Variable;
            b.Assign(retValue,
                     new CodeCast(mi.ReturnType,
                                  b.CallFunc(m.GetThis(), beginProcessMethod, argMethodInfo, argOperName, paramsRef, callbackRef, stateRef)));

            b.Return(retValue);
        }
Exemplo n.º 30
0
        public void ClonesParameters()
        {
            var method = new CodeMethod {
                Name = "method1"
            };

            method.AddParameter(new CodeParameter {
                Name = "param1"
            });
            var clone = method.Clone() as CodeMethod;

            Assert.Equal(method.Name, clone.Name);
            Assert.Single(method.Parameters);
            Assert.Equal(method.Parameters.First().Name, clone.Parameters.First().Name);
        }
Exemplo n.º 31
0
 protected override CodeElement CreateCodeElement(string name, string fullName, CodeLocation location, CodeElement parent)
 {
     CodeMethod method = new CodeMethod(name, fullName, location, parent);
     return method;
 }