public void ParseWithCodeModelWithCreateResourceMethod()
        {
            CodeModel codeModel = New <CodeModel>();

            codeModel.ApiVersion = "2016-01-01";

            Parameter body = New <Parameter>(new
            {
                Location = ParameterLocation.Body,
                Type     = New <CompositeType>(),
            });

            CompositeType responseBody = New <CompositeType>();

            responseBody.Extensions.Add("x-ms-azure-resource", true);

            const string url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Mock.Provider/mockResourceNames/{mockResourceName}";

            Method method = New <Method>(new
            {
                HttpMethod = HttpMethod.Put,
                ReturnType = new Response(responseBody, null),
                Url        = url,
            });

            method.Add(body);

            codeModel.Add(method);

            IDictionary <string, ResourceSchema> schemas = ResourceSchemaParser.Parse(codeModel);

            Assert.NotNull(schemas);
            Assert.Equal(1, schemas.Count);

            ResourceSchema schema = schemas["Mock.Provider"];

            Assert.Equal("http://schema.management.azure.com/schemas/2016-01-01/Mock.Provider.json#", schema.Id);
            Assert.Equal("http://json-schema.org/draft-04/schema#", schema.Schema);
            Assert.Equal("Mock.Provider", schema.Title);
            Assert.Equal("Mock Provider Resource Types", schema.Description);
            Assert.Equal(1, schema.ResourceDefinitions.Count);
            Assert.Equal("mockResourceNames", schema.ResourceDefinitions.Keys.Single());
            Assert.Equal(
                new JsonSchema()
            {
                JsonType    = "object",
                Description = "Mock.Provider/mockResourceNames"
            }
                .AddProperty("type", JsonSchema.CreateStringEnum("Mock.Provider/mockResourceNames"), true)
                .AddProperty("apiVersion", JsonSchema.CreateStringEnum("2016-01-01"), true),
                schema.ResourceDefinitions["mockResourceNames"]);
            Assert.NotNull(schema.Definitions);
            Assert.Equal(0, schema.Definitions.Count);
        }
Beispiel #2
0
        public void add_two_integers_should_success()
        {
            int num1 = 3;
            int num2 = 5;

            int expected = 8;

            int actual = method.Add(num1, num2);

            Assert.Equal(expected, actual);
        }
        private void BuildMethodParameters(Method method)
        {
            foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
            {
                var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
                method.Add(parameter);

                StringBuilder parameterName = new StringBuilder(parameter.Name);
                parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
                                                                               parameterName);

                if (swaggerParameter.In == ParameterLocation.Header)
                {
                    method.RequestHeaders[swaggerParameter.Name] =
                        string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
                }
            }
        }
        private void Push(string methodName)
        {
            if (OutputConnection != null && OutputConnection.State == ConnectionState.Closed)
            {
                throw new Exception(TopMethod + " - Output Connection is closed");
            }
            if (InputConnection != null && InputConnection.State == ConnectionState.Closed)
            {
                throw new Exception(TopMethod + " - Input Connection is closed");
            }

            if (MeasurePerformance)
            {
                Method.Add(methodName); // push the stack
                InfoAspect.Measuring(methodName);
                Level++;
            }
            if (Level != Method.Count + 1)
            {
                Pause();
            }
        }
Beispiel #5
0
        public override void Execute(IList <Token> tokens, ref int i)
        {
            var currentToken = tokens[i];

            if (literal != null)
            {
                //ParserHelper.PushToStack(PrevMember, Method);
                //var member = ParserHelper.GetMember(literal, DefinedTypes, Method.Locals, TypeBuilder);

                if (PrevMember is MemberInfo[] members)
                {
                    PrevMember = members[0];
                }

                switch (PrevMember)
                {
                case FieldInfo field:
                    Method.StoreField(field);
                    break;

                case Local local:
                    Method.StoreLocal(local);
                    break;

                default:
                    ExceptionManager.ThrowCompiler(ErrorCode.NotPossibleToSetValue, "", currentToken.Line);
                    break;
                }
            }

            if (IsInner)
            {
                if (tokens[i + 1].TokenType != TokenType.Operator)
                {
                    ParserHelper.PushToStack(tokens[i].Value, Method, DefinedTypes, TypeBuilder, AsmBuilder);
                    i++;
                }
                else
                {
                    var left  = tokens[i].Value;
                    var right = tokens[i + 2].Value;

                    //todo узнавать, переменная, константа или функция (вроде как сделал)
                    ParserHelper.PushToStack(left, Method, DefinedTypes, TypeBuilder, AsmBuilder);
                    ParserHelper.PushToStack(right, Method, DefinedTypes, TypeBuilder, AsmBuilder);

                    //todo добавить больше операций
                    switch (tokens[i + 1].Value)
                    {
                    case "+":
                        Method.Add();
                        break;

                    case "-":
                        Method.Subtract();
                        break;

                    case "*":
                        Method.Multiply();
                        break;

                    case "/":
                        Method.Divide();
                        break;
                    }
                    i += 3;
                }
            }
            else
            {
                if (currentToken.TokenType == TokenType.Type)
                {
                    if (tokens[i + 1].TokenType == TokenType.Identifier)
                    {
                        if (!ParserHelper.CheckUnusedLocal(tokens, _methodBodyState.FirstInstructionIndex,
                                                           tokens[i + 1].Value))
                        {
                            var type = DefinedTypes[currentToken.Value];
                            Method.DeclareLocal(type, tokens[i + 1].Value);
                            i++;
                        }
                    }
                    i++;
                    PrevMember = DefinedTypes[currentToken.Value];
                }
                else if (currentToken.Value == "=") //(currentToken.TokenType == TokenType.Operator)
                {
                    StateStack.Push(new InstructionState(StateStack, DefinedTypes, AsmBuilder, TypeBuilder, Method)
                    {
                        IsInner = true
                    });
                    literal = tokens[i - 1].Value;
                    i++;
                    return;
                    //ProcessOperator(tokens, ref i);
                }
                else if (currentToken.TokenType == TokenType.Identifier)
                {
                    if (tokens[i + 1].TokenType == TokenType.OpenBrace)
                    {
                        StateStack.Push(new CallMethodState(StateStack, DefinedTypes, AsmBuilder, TypeBuilder, Method));
                        return;
                    }
                    PrevMember = ParserHelper.GetMember(currentToken.Value, DefinedTypes, Method.Locals, TypeBuilder, AsmBuilder);
                    i++;
                }
                else if (currentToken.Value == "ret")
                {
                    var nextToken = tokens[i + 1];
                    if (nextToken.TokenType == TokenType.Identifier ||
                        nextToken.TokenType == TokenType.Constant)
                    {
                        ParserHelper.PushToStack(nextToken.Value, Method, DefinedTypes, TypeBuilder, AsmBuilder);
                        i++;
                    }
                    Method.Return();
                    i++;
                }
                else if (currentToken.Value == ".")
                {
                    MemberInfo[] members;
                    if (PrevMember is Type type)
                    {
                        type    = DefinedTypes[type.FullName];
                        members = type.GetMember(tokens[i + 1].Value);
                    }
                    else
                    {
                        members = PrevMember.GetType().GetMember(tokens[i + 1].Value);
                    }
                    if (members.Length == 0)
                    {
                        ExceptionManager.ThrowCompiler(ErrorCode.UnexpectedToken, string.Empty, tokens[i + 1].Line);
                    }

                    var currMember = members[0];

                    if (currMember is MethodInfo)
                    {
                        i++;
                        ParserHelper.PushToStack(PrevMember, Method);
                        Method.Box(ParserHelper.GetMemberType(PrevMember));

                        var callMethodState = new CallMethodState(StateStack, DefinedTypes, AsmBuilder,
                                                                  ((MethodInfo)currMember).DeclaringType, Method);
                        StateStack.Push(callMethodState);
                        callMethodState.Execute(tokens, ref i);
                        return;
                    }
                    else
                    {
                        i += 2;
                    }
                    PrevMember = currMember;
                }
            }

            StateStack.Pop();
        }
Beispiel #6
0
        private void ProcessOperator(IList <Token> tokens, ref int i)
        {
            if (tokens[i].Value == "=")
            {
                if (!_methodBodyState.UnusedLocals.Contains(tokens[i - 1].Value))
                {
                    //todo узнавать, это присвоение значения или результата вычислений, если последнее, то перенаправлять в следующий if


                    var variable = tokens[i - 1].Value;
                    //todo узнавать, переменная, константа или функция (вроде как сделал)
                    ParserHelper.PushToStack(tokens[i + 1].Value, Method, DefinedTypes, TypeBuilder, AsmBuilder);
                    //todo узнавать, переменная или поле (вроде как сделал)
                    var member = ParserHelper.GetMember(variable, DefinedTypes, Method.Locals, TypeBuilder, AsmBuilder);
                    switch (member)
                    {
                    case FieldInfo fieldInfo:
                        Method.StoreField(fieldInfo);
                        break;

                    case Local local:
                        Method.StoreLocal(local);
                        break;

                    default:
                        //todo NotPossibleToSetValue
                        ExceptionManager.ThrowCompiler(ErrorCode.NotPossibleToSetValue, "", tokens[i].Line);
                        break;
                    }
                }
                i += 2;
            }
            else
            {
                var left  = tokens[i - 1].Value;
                var right = tokens[i + 1].Value;

                //todo узнавать, переменная, константа или функция (вроде как сделал)
                ParserHelper.PushToStack(left, Method, DefinedTypes, TypeBuilder, AsmBuilder);
                ParserHelper.PushToStack(right, Method, DefinedTypes, TypeBuilder, AsmBuilder);

                //todo добавить больше операций
                switch (tokens[i].Value)
                {
                case "+":
                    Method.Add();
                    break;

                case "-":
                    Method.Subtract();
                    break;

                case "*":
                    Method.Multiply();
                    break;

                case "/":
                    Method.Divide();
                    break;
                }
                i += 2;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Adds ListNext() method for each List method with x-ms-pageable extension.
        /// </summary>
        /// <param name="codeModelient"></param>
        /// <param name="codeNamer"></param>
        public static void AddPageableMethod(CodeModel codeModel)
        {
            if (codeModel == null)
            {
                throw new ArgumentNullException("codeModel");
            }

            foreach (var method in codeModel.Methods.Distinct(each => each.Group + each.Name).ToArray())
            {
                if (method.Extensions.ContainsKey(PageableExtension))
                {
                    var pageableExtension = JsonConvert.DeserializeObject <PageableExtension>(method.Extensions[PageableExtension].ToString());
                    if (string.IsNullOrWhiteSpace(pageableExtension.NextLinkName))
                    {
                        continue;
                    }

                    Method nextLinkMethod = null;
                    if (!string.IsNullOrEmpty(pageableExtension.OperationName))
                    {
                        nextLinkMethod = codeModel.Methods.FirstOrDefault(m =>
                                                                          pageableExtension.OperationName.EqualsIgnoreCase(m.SerializedName));
                        if (nextLinkMethod != null)
                        {
                            nextLinkMethod.Extensions["nextLinkMethod"] = true;
                            method.Extensions["nextMethodName"]         = nextLinkMethod.Name;
                            method.Extensions["nextMethodGroup"]        = nextLinkMethod.Group;
                        }
                    }

                    if (nextLinkMethod == null)
                    {
                        nextLinkMethod = Duplicate <Method>(method);

                        if (!string.IsNullOrEmpty(pageableExtension.OperationName))
                        {
                            nextLinkMethod.Name = CodeNamer.Instance.GetMethodName(SwaggerModeler.GetMethodName(
                                                                                       new Operation {
                                OperationId = pageableExtension.OperationName
                            }));
                            nextLinkMethod.Group = CodeNamer.Instance.GetMethodGroupName(SwaggerModeler.GetMethodGroup(
                                                                                             new Operation {
                                OperationId = pageableExtension.OperationName
                            }));
                        }
                        else
                        {
                            nextLinkMethod.Name = nextLinkMethod.Name + "Next";
                        }
                        method.Extensions["nextMethodName"]         = nextLinkMethod.Name;
                        method.Extensions["nextMethodGroup"]        = nextLinkMethod.Group;
                        nextLinkMethod.Extensions["nextLinkMethod"] = true;
                        nextLinkMethod.ClearParameters();
                        nextLinkMethod.Url           = "{nextLink}";
                        nextLinkMethod.IsAbsoluteUrl = true;
                        var nextLinkParameter = New <Parameter>(new
                        {
                            Name           = "nextPageLink",
                            SerializedName = "nextLink",
                            ModelType      = New <PrimaryType>(KnownPrimaryType.String),
                            Documentation  = "The NextLink from the previous successful call to List operation.",
                            IsRequired     = true,
                            Location       = ParameterLocation.Path
                        });
                        nextLinkParameter.Extensions[SkipUrlEncodingExtension] = true;
                        nextLinkMethod.Add(nextLinkParameter);

                        // Need copy all the header parameters from List method to ListNext method
                        foreach (var param in method.Parameters.Where(p => p.Location == ParameterLocation.Header))
                        {
                            nextLinkMethod.Add(Duplicate(param));
                        }

                        // Copy all grouped parameters that only contain header parameters
                        nextLinkMethod.InputParameterTransformation.Clear();
                        method.InputParameterTransformation.GroupBy(t => t.ParameterMappings[0].InputParameter)
                        .ForEach(grouping => {
                            if (grouping.All(t => t.OutputParameter.Location == ParameterLocation.Header))
                            {
                                // All grouped properties were header parameters, reuse data type
                                nextLinkMethod.Add(grouping.Key);
                                grouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add(t));
                            }
                            else if (grouping.Any(t => t.OutputParameter.Location == ParameterLocation.Header))
                            {
                                // Some grouped properties were header parameters, creating new data types
                                var headerGrouping = grouping.Where(t => t.OutputParameter.Location == ParameterLocation.Header);
                                headerGrouping.ForEach(t => nextLinkMethod.InputParameterTransformation.Add((ParameterTransformation)t.Clone()));
                                var newGroupingParam = CreateParameterFromGrouping(headerGrouping, nextLinkMethod, codeModel);
                                nextLinkMethod.Add(newGroupingParam);
                                //grouping.Key.Name = newGroupingParam.Name;
                                // var inputParameter = (Parameter) nextLinkMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter.Clone();
                                var inputParameter  = Duplicate(nextLinkMethod.InputParameterTransformation.First().ParameterMappings[0].InputParameter);
                                inputParameter.Name = CodeNamer.Instance.GetParameterName(newGroupingParam.Name);

                                inputParameter.IsRequired = newGroupingParam.IsRequired;
                                nextLinkMethod.InputParameterTransformation.ForEach(t => t.ParameterMappings[0].InputParameter = inputParameter);
                            }
                        });

                        codeModel.Add(nextLinkMethod);
                    }
                }
            }
        }
 // ----------------------------------------------------------------------------------------
 /// <!-- Add -->
 /// <summary>
 ///
 /// </summary>
 /// <param name="methodName"></param>
 public void Add(string methodName)
 {
     Method.Add(methodName);
 }