/// <summary>Visits a constructor invocation.</summary>
        /// <param name="cons">Construction.</param>
        /// <returns>Resulting expression to visit.</returns>
        public override void VisitMethodCall(MethodCall methodCall)
        {
            if (methodCall != null)
            {
                MemberBinding callBinding = methodCall.Callee as MemberBinding;
                if (callBinding != null)
                {
                    Method method = callBinding.BoundMember as Method;
                    if (method != null &&
                        method.DeclaringType.DeclaringModule.ContainingAssembly.Name == "Microsoft.Spatial" &&
                        method.DeclaringType.FullName == "Microsoft.Spatial.SpatialImplementation" &&
                        method.Name.Name == "get_Operations" &&
                        method.IsPublic &&
                        method.NodeType == NodeType.Method)
                    {
                        if (methodUnderCheck.Name.Name != "VerifyAndGetNonNullOperations")
                        {
                            this.Problems.Add(new Problem(GetResolution(methodUnderCheck.FullName)));
                        }
                    }
                }
            }

            base.VisitMethodCall(methodCall);
        }
Example #2
0
		public async Task<List<PostInfo>> GetRecentPostsAsync(int numposts)
		{
			Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL);
			MethodCall methodCall = new MethodCall("metaWeblog.getRecentPosts");
			methodCall.Parameters.Add(this.BlogConnectionInfo.BlogID);
			methodCall.Parameters.Add(this.BlogConnectionInfo.Username);
			methodCall.Parameters.Add(this.BlogConnectionInfo.Password);
			methodCall.Parameters.Add(numposts);
			service.Cookies = this.BlogConnectionInfo.Cookies;
			MethodResponse methodResponse = await service.ExecuteAsync(methodCall);
			Value value = methodResponse.Parameters[0];
			XmlRPC.Array array = (XmlRPC.Array)value;
			List<PostInfo> list = new List<PostInfo>();
			foreach (Value current in array)
			{
				Struct @struct = (Struct)current;
				list.Add(new PostInfo
				{
					Title = @struct.Get<StringValue>("title", StringValue.NullString).String,
					DateCreated = new DateTime?(@struct.Get<DateTimeValue>("dateCreated").Data),
					Link = @struct.Get<StringValue>("link", StringValue.NullString).String,
					PostID = @struct.Get<StringValue>("postid", StringValue.NullString).String,
					UserID = @struct.Get<StringValue>("userid", StringValue.NullString).String,
					CommentCount = @struct.Get<IntegerValue>("commentCount", 0).Integer,
					PostStatus = @struct.Get<StringValue>("post_status", StringValue.NullString).String,
					PermaLink = @struct.Get<StringValue>("permaLink", StringValue.NullString).String,
					Description = @struct.Get<StringValue>("description", StringValue.NullString).String
				});
			}
			return list;
		}
        /// <summary>Visits a method call.</summary>
        /// <param name="methodCall">Method call.</param>
        /// <returns>Resulting expression to visit.</returns>
        public override void VisitMethodCall(MethodCall methodCall)
        {
            if (methodCall != null)
            {
                MemberBinding callBinding = methodCall.Callee as MemberBinding;
                if (callBinding != null)
                {
                    /* 
                        typeof(DataServiceCollection<>) is compiled to IL as: 
                            ldtoken [Microsoft.OData.Client]Microsoft.OData.Client.DataServiceCollection`1
                            call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
                     */
                    Method method = callBinding.BoundMember as Method;
                    if (method.Name.Name == "GetTypeFromHandle" &&
                        method.DeclaringType.FullName == "System.Type")
                    {
                        Debug.Assert(methodCall.Operands.Count == 1);
                        Debug.Assert(methodCall.Operands[0].NodeType == NodeType.Ldtoken);

                        ClassNode classType = (((Literal)(((UnaryExpression)methodCall.Operands[0]).Operand)).Value) as ClassNode;
                        if (classType != null && classType.FullName == "Microsoft.OData.Client.DataServiceCollection`1")
                        {
                            if (methodUnderCheck.DeclaringType.FullName != "System.Data.Serices.Client.WebUtil" &&
                                methodUnderCheck.Name.Name != "GetDataServiceCollectionOfTType")
                            {
                                this.Problems.Add(new Problem(GetResolution(methodUnderCheck.FullName)));
                            }
                        }
                    }
                }
            }

            base.VisitMethodCall(methodCall);
        }
 public InterpretedMethod(string name, string [] parameters,IEvaluable body)
 {
     this.name=name;
     this.parameters=parameters;
     this.body=body;
     this.delegatedMethodCall = null;
 }
        private static void GenerateMethod()
        {
            Method method = new Method();
            method.Name = "MyNewProc";
            method.MethodType = MethodTypeEnum.Void;
            Param newParam = new Param();
            TypeReferenceExpression newTypeReferenceExpression = new TypeReferenceExpression();
            newTypeReferenceExpression.Name = CodeRush.Language.GetSimpleTypeName("System.Int32");
            newParam.MemberTypeReference = newTypeReferenceExpression;
            newParam.Name = "MyKillerParameter";

            method.Parameters.Add(newParam);

            MethodCall statement = new MethodCall();
            statement.Name = "Start";
            //UnaryIncrement newUnaryIncrement = new UnaryIncrement();
            //ElementReferenceExpression elementReferenceExpression = new ElementReferenceExpression(newParam.Name);
            //newUnaryIncrement.Expression = elementReferenceExpression;
            //statement.AddDetailNode(newUnaryIncrement);
            //int MyKillerParameter = 0;
            //MyKillerParameter++;

            method.AddNode(statement);
            string newCode = CodeRush.Language.GenerateElement(method);
            TextDocument activeTextDocument = CodeRush.Documents.ActiveTextDocument;
            if (activeTextDocument == null)
                return;

            activeTextDocument.InsertText(activeTextDocument.ActiveView.Caret.SourcePoint, newCode);
        }
        /// <summary>Visits a constructor invocation.</summary>
        /// <param name="cons">Construction.</param>
        /// <returns>Resulting expression to visit.</returns>
        public override void VisitMethodCall(MethodCall methodCall)
        {
            if (methodCall != null)
            {
                MemberBinding callBinding = methodCall.Callee as MemberBinding;
                if (callBinding != null)
                {
                    Method method = callBinding.BoundMember as Method;
                    if (method != null &&
                        method.DeclaringType.FullName == "Microsoft.OData.Client.EntityDescriptor" &&
                        method.Name.Name != "get_Entity" &&
                        method.Name.Name != "get_StreamDescriptors" &&
                        method.Name.Name != "set_ETag" &&
                        method.IsPublic &&
                        method.NodeType == NodeType.Method)
                    {
                        if (methodUnderCheck.DeclaringType.FullName == "Microsoft.OData.Client.BaseSaveResult" ||
                            methodUnderCheck.DeclaringType.FullName == "Microsoft.OData.Client.SaveResult")
                        {
                            this.Problems.Add(new Problem(GetResolution(methodUnderCheck.FullName)));
                        }
                    }
                }
            }

            base.VisitMethodCall(methodCall);
        }
Example #7
0
        public override void VisitMethodCall(MethodCall call)
        {
            if (call != null)
            {
                MemberBinding binding = call.Callee as MemberBinding;
                Method calleeMethod = (binding == null) ? null : binding.BoundMember as Method;
                if (calleeMethod != null)
                {

                    string fullName = calleeMethod.FullName;
                    if (exploreGraph && alreadyExplored.Add(fullName))
                    {
                        // see if the method(s) is is the call graph
                        Visit(calleeMethod);
                    }

                    int hits;
                    if (this.timesFound.TryGetValue(fullName, out hits))
                    {
                        this.timesFound[fullName] = hits + 1;
                    }
                }
            }

            base.VisitMethodCall(call);
        }
 public override Statement VisitAssignmentStatement(AssignmentStatement assignment)
 {
   MemberBinding binding = assignment.Target as MemberBinding;
   if (binding != null) 
   {
     Expression target = VisitExpression(binding.TargetObject);
     Field boundMember = (Field) binding.BoundMember;
     Expression source = VisitExpression(assignment.Source);
     if (!boundMember.IsStatic && !boundMember.DeclaringType.IsValueType && boundMember.DeclaringType.Contract != null && boundMember.DeclaringType.Contract.FramePropertyGetter != null && boundMember != boundMember.DeclaringType.Contract.FrameField) 
     {
       Local targetLocal = new Local(boundMember.DeclaringType);
       Statement evaluateTarget = new AssignmentStatement(targetLocal, target, assignment.SourceContext);
       Local sourceLocal = new Local(boundMember.Type);
       Statement evaluateSource = new AssignmentStatement(sourceLocal, source, assignment.SourceContext);
       Expression guard = new MethodCall(new MemberBinding(targetLocal, boundMember.DeclaringType.Contract.FramePropertyGetter), null, NodeType.Call, SystemTypes.Guard);
       Statement check = new ExpressionStatement(new MethodCall(new MemberBinding(guard, SystemTypes.Guard.GetMethod(Identifier.For("CheckIsWriting"))), null, NodeType.Call, SystemTypes.Void));
       Statement stfld = new AssignmentStatement(new MemberBinding(targetLocal, boundMember), sourceLocal, assignment.SourceContext);
       return new Block(new StatementList(new Statement[] {evaluateTarget, evaluateSource, check, stfld}));
     } 
     else
     {
       binding.TargetObject = target;
       assignment.Source = source;
       return assignment;
     }
   }
   else
   {
     return base.VisitAssignmentStatement(assignment);
   }
 }
        public override void VisitMethodCall(MethodCall call)
        {
            var memberBinding = (MemberBinding)call.Callee;
            var member = memberBinding.BoundMember;
            if (member.NodeType == NodeType.Method)
            {
                var method = (Method)member;
                foreach (var dontPassParameterType in Settings.DontPassParameterType)
                {
                    if (dontPassParameterType.FullName == method.FullName)
                    {
                        var infos = Enumerable.Range(1, method.Parameters.Count).GroupJoin(
                            dontPassParameterType.ParameterType,
                            index => index,
                            info => info.Key,
                            (index, info) => info.FirstOrDefault(i => i.Key == index).Value)
                            .ToList();

                        for (var index = 0; index < method.Parameters.Count; index++)
                        {
                            string value;
                            if (dontPassParameterType.ParameterType.TryGetValue(index + 1, out value))
                            {
                                if (call.Operands[index].Type.FullName == value)
                                {
                                    this.Violate(call, method.FullName, index + 1, value);
                                }
                            }
                        }
                    }
                }
            }

            base.VisitMethodCall(call);
        }
        private static bool QualifyParameters(MethodCall methodCall)
        {
            if (methodCall.ArgumentsCount < 1)
                return true;

            var doubleQuotesExpression = methodCall.Arguments[0] as PrimitiveExpression;
            if (doubleQuotesExpression != null
                && doubleQuotesExpression.PrimitiveType == PrimitiveType.String
                && (doubleQuotesExpression.Name == "\"\"" || doubleQuotesExpression.Name == "@\"\""))
                return true;

            var nullExpression = methodCall.Arguments[0] as PrimitiveExpression;
            if (nullExpression != null
                && nullExpression.PrimitiveType == PrimitiveType.Void
                && nullExpression.Name == "null")
                return true;

            var stringEmptyExpression = methodCall.Arguments[0] as ElementReferenceExpression;
            if (stringEmptyExpression != null
                && stringEmptyExpression.Name == "Empty"
                && stringEmptyExpression.Qualifier != null
                && stringEmptyExpression.Qualifier.Name.ToLowerInvariant() == "string")
                return true;

            return false;
        }
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            Expression retExpr = null;

            if (node.Method.Name == _functionName)
            {
                var str = node.ToString();
                MethodCall call;
                if (_methodCalls.TryGetValue(str, out call))
                {
                    ++call.CallCount;
                }
                else
                {
                    call = new MethodCall(node, Expression.Parameter(node.Type, "param" + (_methodCalls.Count)));
                    _methodCalls.Add(str, call);
                }

                retExpr = call.Parameter;
            }
            else
                retExpr = base.VisitMethodCall(node);

            return retExpr;
        }
 public void Analyze(MethodCall methodCall, ISymbolTable context, List<IPreCondition> preConditions)
 {
     Method calleeMethod = IntrospectionUtility.ExtractMethod (methodCall);
       ICustomInference matchingRule = MatchingAnalyzeRule (calleeMethod);
       if (matchingRule != null)
       {
     matchingRule.Analyze (methodCall, context, preConditions);
       }
 }
 public override Expression VisitMethodCall(MethodCall call)
 {
   call.Operands = this.VisitExpressionList(call.Operands);
   if (call.Callee != null) 
   {
     call.Callee = this.VisitExpression(call.Callee);
   }
   return call;
 }
        public override void VisitMethodCall(MethodCall call) {
            Method method = ((MemberBinding)call.Callee).BoundMember as Method;

            if ((method != null) &&
                (method.DeclaringType.FullName == "System.Script") &&
                (method.Name.Name == "Literal")) {
                Problems.Add(new Problem(GetResolution(), call.SourceContext));
            }
        }
 public Fragment InferFragmentType(MethodCall methodCall, ISymbolTable context)
 {
     Fragment returnFragment = Fragment.CreateEmpty();
       Method calleeMethod = IntrospectionUtility.ExtractMethod (methodCall);
       if(_coveredMethods.Contains(calleeMethod.FullName))
       {
     returnFragment = ParameterFragmentUtility.ParameterFragmentIntersection (methodCall, context);
       }
       return returnFragment;
 }
 public byte[] SerializeMethodCall(MethodCall methodCall)
 {
     var wrapper = new MethodCallWrapper(methodCall);
     wrapper.Args = methodCall.Args;
     wrapper.MethodSignature = new string[
         methodCall.MethodSignature != null ? methodCall.MethodSignature.Length : 0];
     for (int i = 0; i < methodCall.MethodSignature.Length; i++)
         wrapper.MethodSignature[i] = this.parseTypeName(methodCall.MethodSignature[i]);
     return this.ToJsonBytes(wrapper);
 }
 public static Fragment ParameterFragmentIntersection(MethodCall methodCall, ISymbolTable context)
 {
     Fragment current = context.InferFragmentType (methodCall.Operands[0]);
       Fragment intersection = current;
       for (int i = 1; i < methodCall.Operands.Count; i++)
       {
     Fragment next = context.InferFragmentType (methodCall.Operands[i]);
     intersection = FragmentIntersection (current, next);
       }
       return intersection;
 }
Example #18
0
        public static bool IsStringConcatMethodCall(MethodCall sourceMethodCall)
        {
            if (sourceMethodCall == null)
            {
                return false;
            }

            var boundMember = ((MemberBinding)sourceMethodCall.Callee).BoundMember;
            var isStringConcatMethodCall = boundMember.FullName.StartsWith("System.String.Concat(", StringComparison.OrdinalIgnoreCase);
            return isStringConcatMethodCall;
        }
 public Fragment InferFragmentType(MethodCall methodCall, ISymbolTable context)
 {
     Fragment fragmentType = Fragment.CreateEmpty();
       Method calleeMethod = IntrospectionUtility.ExtractMethod (methodCall);
       ICustomInference matchingRule = MatchingInferRule (calleeMethod);
       if (matchingRule != null)
       {
     fragmentType = matchingRule.InferFragmentType (methodCall, context);
       }
       return fragmentType;
 }
Example #20
0
        public override void VisitMethodCall(MethodCall call)
        {
            if (call.Method() != null)
            {
                if (call.Method().Parameters.Any(a => a.Type.FullName == "System.Web.Mvc.JsonRequestBehavior"))
                {
                    this.Problems.Add(new Problem(this.GetResolution(), (Node)call));
                }
            }

            base.VisitMethodCall(call);
        }
Example #21
0
        public override void VisitMethodCall(MethodCall call)
        {
            if (call.Method() != null)
            {
                if ((call.Method().Name.Name == "SendMail" || call.Method().Name.Name == "SendBulkMail") && call.Method().DeclaringType.FullName == "CDS.Core.Utils.EMail")
                {
                    Problems.Add(new Problem(this.GetResolution()));
                }
            }

            base.VisitMethodCall(call);
        }
        private static string GetTypeOfNthParamOfMethod(int ParamIndex, MethodCall MethodCall)
        {
            MethodReferenceExpression OuterMethodReference = (MethodCall.Nodes[0] as DevExpress.CodeRush.StructuralParser.MethodReferenceExpression);

            var Declaration1 = OuterMethodReference.GetDeclaration() as Method;
            // Previous line will return null if any parameter isn't explicitly calculable.
            if (Declaration1 == null)
                return ""; // Suggest void. Wrong, but best available option.

            var Param = Declaration1.Parameters[ParamIndex] as Param;
            return Param.GetTypeName();
        }
Example #23
0
        public override void VisitMethodCall(MethodCall call)
        {
            if (call.Method() != null)
            {
                if (call.Method().IsStatic && call.Method().Name.Name.StartsWith("get_Current")
                    && call.Method().DeclaringType.FullName != "System.Globalization.CultureInfo")
                {
                    this.Problems.Add(new Problem(this.GetResolution(call.Method().FullName), (Node)call));
                }
            }

            base.VisitMethodCall(call);
        }
 private void AddEntryPointMethod(Compilation compilation) {
   List<Expression> args = new List<Expression>(1);
   args.Add(new CompileTimeConstant(0, SourceDummy.SourceLocation));
   Expression createInstance = new CreateObjectInstance(new NamedTypeExpression(new SimpleName(this.Name, SourceDummy.SourceLocation, false)), args, SourceDummy.SourceLocation);
   Expression callMain = new MethodCall(
     new QualifiedName(createInstance, new SimpleName(compilation.NameTable.GetNameFor("Main"), SourceDummy.SourceLocation, false), SourceDummy.SourceLocation),
     Expression.EmptyCollection, SourceDummy.SourceLocation);
   List<Statement> body = new List<Statement>(1);
   body.Add(new ExpressionStatement(callMain));
   MethodDeclaration entryPointMethod = new MethodDeclaration(null, MethodDeclaration.Flags.Static, TypeMemberVisibility.Public,
     TypeExpression.For(compilation.PlatformType.SystemVoid.ResolvedType), null, new NameDeclaration(compilation.NameTable.GetNameFor("EntryPoint"), SourceDummy.SourceLocation), null, 
     null, null, new BlockStatement(body, this.SourceLocation), this.SourceLocation);
   this.members.Add(entryPointMethod);
 }
      private static void CreateMemberCalls()
      {
        Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName);
        Type csharpBinderFlagsType = Type.GetType(CSharpBinderFlagsTypeName);
        Type binderType = Type.GetType(BinderTypeName);

        Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType);

        MethodInfo getMemberMethod = binderType.GetMethod("GetMember", BindingFlags.Public | BindingFlags.Static, null, new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }, null);
        _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getMemberMethod);

        MethodInfo setMemberMethod = binderType.GetMethod("SetMember", BindingFlags.Public | BindingFlags.Static, null, new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }, null);
        _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(setMemberMethod);
      }
Example #26
0
        public MethodDefinition(SrcMLArchive archive, MethodData data, MethodCall fromCall) {
            this.Archive = archive;
            this.SourceCall = fromCall;
            this.Data = data;

            this.isValid = false;

            this.Location = data.PrimaryLocation;
            this.FullName = Data.GetFullName();
            this.Id = DataHelpers.GetLocation(Location);
            this.Path = Location.SourceFileName;

            this.Signature = GetMethodSignature();
        }
Example #27
0
        public override void VisitMethodCall(MethodCall call)
        {
            if (IsSqlExecutingFunction(call.Method()))
            {
                Problems.Add(new Problem(this.GetResolution(), call.SourceContext));
            }

            if (!call.Method().DeclaringType.FullName.StartsWith("System.") && !call.Method().DeclaringType.FullName.StartsWith("Microsoft.") && call.Method().DeclaringType != _currentType && call.Method().FullName != "CDS.Core.Utils.Inspection.SafeSqlBuilder.#ctor")
            {
                Problems.Add(new Problem(this.GetResolution(), call.SourceContext));
            }

            base.VisitMethodCall(call);
        }
    internal IWrappedDictionary CreateWrapper(object dictionary)
    {
      if (dictionary is IDictionary)
        return new DictionaryWrapper<object, object>((IDictionary)dictionary);

      if (_genericWrapperType == null)
      {
        _genericWrapperType = ReflectionUtils.MakeGenericType(typeof(DictionaryWrapper<,>), DictionaryKeyType, DictionaryValueType);

        ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType });
        _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(genericWrapperConstructor);
      }

      return (IWrappedDictionary)_genericWrapperCreator(null, dictionary);
    }
Example #29
0
        public override void VisitMethodCall(MethodCall call)
        {
            var memberBinding = (MemberBinding)call.Callee;
            var member = memberBinding.BoundMember;
            if (member.NodeType == NodeType.Method)
            {
                var method = (Method)member;
                if (Settings.DontUseMethod.Contains(method.FullName))
                {
                    this.Violate(call, method.FullName);
                }
            }

            base.VisitMethodCall(call);
        }
        public override void VisitMethodCall(MethodCall call)
        {
            if (call.Method() != null)
            {
                if (!call.Method().DeclaringType.DeclaringModule.ContainingAssembly.IsSystemAssembly() //only need to check our own stuff, we can't do data access through a MSFT function from our web projects
                    && call.Method().DeclaringType.DeclaringModule.ContainingAssembly.Name != "CDS.Core.Utils" //MOD: we've whitelisted some stuff, here
                    && call.Method().DeclaringType.DeclaringModule.ContainingAssembly.Name != "CDS.ProxyFactory"
                    && !call.Method().IsPropertyAccessor()) //call me overconfident, but I think we can assume property accessors aren't writing to the database
                {
                    KeywordViolations(call.Method());
                }
            }

            base.VisitMethodCall(call);
        }
        public override MethodCall <T, object> CreateMethodCall <T>(MethodBase method)
        {
            ValidationUtils.ArgumentNotNull(method, "method");

            Type type = typeof(object);

            ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
            ParameterExpression argsParameterExpression   = Expression.Parameter(typeof(object[]), "args");

            ParameterInfo[] parametersInfo = method.GetParameters();

            Expression[] argsExpression = new Expression[parametersInfo.Length];

            for (int i = 0; i < parametersInfo.Length; i++)
            {
                Expression indexExpression = Expression.Constant(i);

                Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);

                paramAccessorExpression = EnsureCastExpression(paramAccessorExpression, parametersInfo[i].ParameterType);

                argsExpression[i] = paramAccessorExpression;
            }

            Expression callExpression;

            if (method.IsConstructor)
            {
                callExpression = Expression.New((ConstructorInfo)method, argsExpression);
            }
            else if (method.IsStatic)
            {
                callExpression = Expression.Call((MethodInfo)method, argsExpression);
            }
            else
            {
                Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);

                callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
            }

            if (method is MethodInfo)
            {
                MethodInfo m = (MethodInfo)method;
                if (m.ReturnType != typeof(void))
                {
                    callExpression = EnsureCastExpression(callExpression, type);
                }
                else
                {
                    callExpression = Expression.Block(callExpression, Expression.Constant(null));
                }
            }
            else
            {
                callExpression = EnsureCastExpression(callExpression, type);
            }

            LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall <T, object>), callExpression, targetParameterExpression, argsParameterExpression);

            MethodCall <T, object> compiled = (MethodCall <T, object>)lambdaExpression.Compile();

            return(compiled);
        }
Example #32
0
    private void AddFactoryMethodArguments(
        MethodInfo factory,
        MethodCall factoryMethodCall,
        List <ApiCall> quotedValues)
    {
        foreach (var factoryMethodParameter in factory.GetParameters())
        {
            var parameterName = factoryMethodParameter.Name;
            var parameterType = factoryMethodParameter.ParameterType;

            ApiCall quotedCodeBlock = FindValue(parameterName, quotedValues);

            // special case to prefer SyntaxFactory.IdentifierName("C") to
            // SyntaxFactory.IdentifierName(Syntax.Identifier("C"))
            if (parameterName == "name" && parameterType == typeof(string))
            {
                quotedCodeBlock = quotedValues.First(a => a.Name == "Identifier");
                var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall;
                if (methodCall != null && methodCall.Name == SyntaxFactory("Identifier"))
                {
                    if (methodCall.Arguments.Count == 1)
                    {
                        factoryMethodCall.AddArgument(methodCall.Arguments[0]);
                    }
                    else
                    {
                        factoryMethodCall.AddArgument(quotedCodeBlock);
                    }

                    quotedValues.Remove(quotedCodeBlock);
                    continue;
                }
            }

            // special case to prefer SyntaxFactory.ClassDeclarationSyntax(string) instead of
            // SyntaxFactory.ClassDeclarationSyntax(SyntaxToken)
            if (parameterName == "identifier" && parameterType == typeof(string))
            {
                var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall;
                if (methodCall != null &&
                    methodCall.Name == SyntaxFactory("Identifier") &&
                    methodCall.Arguments.Count == 1)
                {
                    factoryMethodCall.AddArgument(methodCall.Arguments[0]);
                    quotedValues.Remove(quotedCodeBlock);
                    continue;
                }
            }

            if (quotedCodeBlock != null)
            {
                factoryMethodCall.AddArgument(quotedCodeBlock);
                quotedValues.Remove(quotedCodeBlock);
            }
            else if (!factoryMethodParameter.IsOptional)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Couldn't find value for parameter '{0}' of method '{1}'. Go to QuotePropertyValues() and add your node type to the exception list.",
                              parameterName,
                              factory));
            }
        }
    }
Example #33
0
        protected SetupPhrase(MethodCall setup)
        {
            Debug.Assert(setup != null);

            this.setup = setup;
        }
        public static object ReadMethodCall(BinaryElement elem, BinaryReader reader, bool hasHeaders, HeaderHandler headerHandler, BinaryFormatter formatter)
        {
            if (elem != BinaryElement.MethodCall)
            {
                throw new SerializationException("Invalid format. Expected BinaryElement.MethodCall, found " + elem);
            }
            MethodFlags methodFlags = (MethodFlags)reader.ReadInt32();

            if (reader.ReadByte() != 18)
            {
                throw new SerializationException("Invalid format");
            }
            string value = reader.ReadString();

            if (reader.ReadByte() != 18)
            {
                throw new SerializationException("Invalid format");
            }
            string value2 = reader.ReadString();

            object[] array  = null;
            object   value3 = null;
            object   value4 = null;

            object[] array2  = null;
            Header[] headers = null;
            Type[]   value5  = null;
            if ((methodFlags & MethodFlags.PrimitiveArguments) > (MethodFlags)0)
            {
                uint num = reader.ReadUInt32();
                array = new object[num];
                int num2 = 0;
                while ((long)num2 < (long)((ulong)num))
                {
                    Type typeFromCode = BinaryCommon.GetTypeFromCode((int)reader.ReadByte());
                    array[num2] = ObjectReader.ReadPrimitiveTypeValue(reader, typeFromCode);
                    num2++;
                }
            }
            if ((methodFlags & MethodFlags.NeedsInfoArrayMask) > (MethodFlags)0)
            {
                ObjectReader objectReader = new ObjectReader(formatter);
                object       obj;
                objectReader.ReadObjectGraph(reader, hasHeaders, out obj, out headers);
                object[] array3 = (object[])obj;
                if ((methodFlags & MethodFlags.ArgumentsInSimpleArray) > (MethodFlags)0)
                {
                    array = array3;
                }
                else
                {
                    int num3 = 0;
                    if ((methodFlags & MethodFlags.ArgumentsInMultiArray) > (MethodFlags)0)
                    {
                        if (array3.Length > 1)
                        {
                            array = (object[])array3[num3++];
                        }
                        else
                        {
                            array = new object[0];
                        }
                    }
                    if ((methodFlags & MethodFlags.GenericArguments) > (MethodFlags)0)
                    {
                        value5 = (Type[])array3[num3++];
                    }
                    if ((methodFlags & MethodFlags.IncludesSignature) > (MethodFlags)0)
                    {
                        value3 = array3[num3++];
                    }
                    if ((methodFlags & MethodFlags.IncludesLogicalCallContext) > (MethodFlags)0)
                    {
                        value4 = array3[num3++];
                    }
                    if (num3 < array3.Length)
                    {
                        array2 = (object[])array3[num3];
                    }
                }
            }
            else
            {
                reader.ReadByte();
            }
            if (array == null)
            {
                array = new object[0];
            }
            string value6 = null;

            if (headerHandler != null)
            {
                value6 = (headerHandler(headers) as string);
            }
            MethodCall methodCall = new MethodCall(new Header[]
            {
                new Header("__MethodName", value),
                new Header("__MethodSignature", value3),
                new Header("__TypeName", value2),
                new Header("__Args", array),
                new Header("__CallContext", value4),
                new Header("__Uri", value6),
                new Header("__GenericArguments", value5)
            });

            if (array2 != null)
            {
                foreach (DictionaryEntry dictionaryEntry in array2)
                {
                    methodCall.Properties[(string)dictionaryEntry.Key] = dictionaryEntry.Value;
                }
            }
            return(methodCall);
        }
Example #35
0
        public void MethodCall_With_Params_Should_Not_Be_Receive()
        {
            var methodCall = new MethodCall("", new object[] { 1 });

            Assert.False(methodCall.IsReceiveHandlerCall);
        }
Example #36
0
        /// <summary>Gets the workshop value of a macro.</summary>
        public static IWorkshopTree CallMacroFunction(ActionSet actionSet, DefinedMethodInstance macro, MethodCall methodCall)
        {
            actionSet = actionSet.ContainVariableAssigner().PackThis();

            // The list containing the macro and all of its overriders, recursively.
            var allOptions = new List <MacroOption>();

            allOptions.Add(new MacroOption(macro));

            // Add overriders to the list.
            var relations = new MethodClassRelations(actionSet.ToWorkshop, macro);

            if (relations.Overriders != null)
            {
                allOptions.AddRange(relations.Overriders.Select(overrider => new MacroOption(overrider)));
            }

            // Add parameters to the assigner.
            for (int i = 0; i < macro.ParameterVars.Length; i++)
            {
                // Origin parameter variables
                actionSet.IndexAssigner.Add(macro.ParameterVars[i].Provider, methodCall.ParameterValues[i]);

                // Overrider parameter variables.
                foreach (var overrider in relations.Overriders)
                {
                    actionSet.IndexAssigner.Add(overrider.ParameterVars[i].Provider, methodCall.ParameterValues[i]);
                }
            }

            // Create the virtual content builder and then return the resulting value.
            var virtualContentBuilder = new MacroContentBuilder(actionSet, allOptions);

            return(virtualContentBuilder.Value);
        }
        internal static IMessage DeserializeMessage(String mimeType, Stream xstm, bool methodRequest, IMessage msg, Header[] h)
        {
            InternalRemotingServices.RemotingTrace("DeserializeMessage");
            InternalRemotingServices.RemotingTrace("MimeType: " + mimeType);

            CoreChannel.DebugOutXMLStream(xstm, "Deserializing");

            Stream fmtStm = null;

            bool bin64encode       = false;
            bool doHeaderBodyAsOne = true;

            if (string.Compare(mimeType, BinaryMimeType, StringComparison.Ordinal) == 0)
            {
                doHeaderBodyAsOne = true;
            }

            if (string.Compare(mimeType, SOAPMimeType, StringComparison.Ordinal) == 0)
            {
                doHeaderBodyAsOne = false;
            }

            if (bin64encode == false)
            {
                fmtStm = xstm;
            }
            else
            {
                InternalRemotingServices.RemotingTrace("***************** Before base64 decode *****");

                long         Position  = xstm.Position;
                MemoryStream inStm     = (MemoryStream)xstm;
                byte[]       byteArray = inStm.ToArray();
                xstm.Position = Position;

                String base64String = Encoding.ASCII.GetString(byteArray, 0, byteArray.Length);

                byte[] byteArrayContent = Convert.FromBase64String(base64String);

                MemoryStream memStm = new MemoryStream(byteArrayContent);

                fmtStm = memStm;
                InternalRemotingServices.RemotingTrace("***************** after base64 decode *****");
            }

            Object             ret;
            IRemotingFormatter fmt = MimeTypeToFormatter(mimeType, false);

            if (doHeaderBodyAsOne == true)
            {
                ret = ((BinaryFormatter)fmt).UnsafeDeserializeMethodResponse(fmtStm, null, (IMethodCallMessage)msg);
            }
            else
            {
                InternalRemotingServices.RemotingTrace("Content");
                InternalRemotingServices.RemotingTrace("***************** Before Deserialize Headers *****");

                InternalRemotingServices.RemotingTrace("***************** After Deserialize Headers *****");

                InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message *****");

                if (methodRequest == true)
                {
                    MethodCall mc = new MethodCall(h);
                    InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodCall *****");
                    fmt.Deserialize(fmtStm, new HeaderHandler(mc.HeaderHandler));
                    ret = mc;
                }
                else
                {
                    IMethodCallMessage mcm = (IMethodCallMessage)msg;
                    MethodResponse     mr  = new MethodResponse(h, mcm);
                    InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodResponse *****");
                    fmt.Deserialize(fmtStm, new HeaderHandler(mr.HeaderHandler));
                    ret = mr;
                }

                InternalRemotingServices.RemotingTrace("***************** After Deserialize Message *****");
            }

            // Workaround to make this method verifiable
            IMessage resMessage = (IMessage)ret;

            InternalRemotingServices.RemotingTrace("CoreChannel::DeserializeMessage OUT");
            CoreChannel.DebugMessage(resMessage);

            return(resMessage);
        }
Example #38
0
 private MethodBase GetMethodInfo(MethodCall objCall)
 {
     return(parent.GetMethodInfo(objCall));
 }
Example #39
0
        /// <summary />
        public override IStatement Rewrite(IForEachStatement forEachStatement)
        {
            ILocalDefinition foreachLocal;
            var key = forEachStatement.Collection.Type.InternedKey;

            ITypeReference   enumeratorType;
            IMethodReference getEnumerator;
            IMethodReference getCurrent;

            var gtir = forEachStatement.Collection.Type as IGenericTypeInstanceReference;

            if (gtir != null)
            {
                var            typeArguments         = gtir.GenericArguments;
                ITypeReference genericEnumeratorType = new Immutable.GenericTypeInstanceReference(this.host.PlatformType.SystemCollectionsGenericIEnumerator, typeArguments, this.host.InternFactory);
                ITypeReference genericEnumerableType = new Immutable.GenericTypeInstanceReference(this.host.PlatformType.SystemCollectionsGenericIEnumerable, typeArguments, this.host.InternFactory);
                enumeratorType = genericEnumeratorType;
                getEnumerator  = new SpecializedMethodReference()
                {
                    CallingConvention = CallingConvention.HasThis,
                    ContainingType    = genericEnumerableType,
                    InternFactory     = this.host.InternFactory,
                    Name                 = this.host.NameTable.GetNameFor("GetEnumerator"),
                    Parameters           = new List <IParameterTypeInformation>(),
                    Type                 = genericEnumeratorType,
                    UnspecializedVersion = new MethodReference()
                    {
                        CallingConvention = CallingConvention.HasThis,
                        ContainingType    = this.host.PlatformType.SystemCollectionsGenericIEnumerable,
                        InternFactory     = this.host.InternFactory,
                        Name       = this.host.NameTable.GetNameFor("GetEnumerator"),
                        Parameters = new List <IParameterTypeInformation>(),
                        Type       = this.host.PlatformType.SystemCollectionsGenericIEnumerator,
                    },
                };
                var getEnumerator2 = (IMethodReference)
                                     IteratorHelper.First(genericEnumerableType.ResolvedType.GetMembersNamed(this.host.NameTable.GetNameFor("GetEnumerator"), false));
                getEnumerator = getEnumerator2;
                getCurrent    = (IMethodReference)IteratorHelper.First(genericEnumeratorType.ResolvedType.GetMembersNamed(this.host.NameTable.GetNameFor("get_Current"), false));
            }
            else
            {
                enumeratorType = this.host.PlatformType.SystemCollectionsIEnumerator;
                getEnumerator  = new MethodReference()
                {
                    CallingConvention = CallingConvention.HasThis,
                    ContainingType    = enumeratorType,
                    InternFactory     = this.host.InternFactory,
                    Name       = this.host.NameTable.GetNameFor("GetEnumerator"),
                    Parameters = new List <IParameterTypeInformation>(),
                    Type       = this.host.PlatformType.SystemCollectionsIEnumerable,
                };
                getCurrent = new MethodReference()
                {
                    CallingConvention = CallingConvention.HasThis,
                    ContainingType    = enumeratorType,
                    InternFactory     = this.host.InternFactory,
                    Name       = this.host.NameTable.GetNameFor("get_Current"),
                    Parameters = new List <IParameterTypeInformation>(),
                    Type       = this.host.PlatformType.SystemObject,
                };
            }

            var initializer = new MethodCall()
            {
                Arguments     = new List <IExpression>(),
                IsStaticCall  = false,
                IsVirtualCall = true,
                MethodToCall  = getEnumerator,
                ThisArgument  = forEachStatement.Collection,
                Type          = enumeratorType,
            };
            IStatement initialization;

            if (!this.foreachLocals.TryGetValue(key, out foreachLocal))
            {
                foreachLocal = new LocalDefinition()
                {
                    Type = enumeratorType, Name = this.host.NameTable.GetNameFor("CS$5$" + this.foreachLocals.Count)
                };
                this.foreachLocals.Add(key, foreachLocal);
                initialization = new LocalDeclarationStatement()
                {
                    InitialValue  = initializer,
                    LocalVariable = foreachLocal,
                };
            }
            else
            {
                initialization = new ExpressionStatement()
                {
                    Expression = new Assignment()
                    {
                        Source = initializer,
                        Target = new TargetExpression()
                        {
                            Definition = foreachLocal,
                            Instance   = null,
                            Type       = foreachLocal.Type,
                        },
                        Type = foreachLocal.Type,
                    },
                };
            }

            var newStmts = new List <IStatement>();

            newStmts.Add(new ExpressionStatement()
            {
                Expression = new Assignment()
                {
                    Source = new MethodCall()
                    {
                        Arguments     = new List <IExpression>(),
                        IsStaticCall  = false,
                        IsVirtualCall = true,
                        MethodToCall  = getCurrent,
                        ThisArgument  = new BoundExpression()
                        {
                            Definition = foreachLocal,
                            Instance   = null,
                        },
                        Type = forEachStatement.Variable.Type,
                    },
                    Target = new TargetExpression()
                    {
                        Definition = forEachStatement.Variable,
                        Instance   = null,
                    },
                    Type = forEachStatement.Variable.Type,
                },
            });
            newStmts.Add(forEachStatement.Body);
            var newBody = new BlockStatement()
            {
                Statements = newStmts,
            };
            var result = new BlockStatement()
            {
                Statements = new List <IStatement>()
                {
                    initialization,
                    new TryCatchFinallyStatement()
                    {
                        TryBody = new BlockStatement()
                        {
                            Statements = new List <IStatement>()
                            {
                                new WhileDoStatement()
                                {
                                    Body      = newBody,
                                    Condition = new MethodCall()
                                    {
                                        Arguments     = new List <IExpression>(),
                                        IsStaticCall  = false,
                                        IsVirtualCall = true,
                                        MethodToCall  = moveNext,
                                        ThisArgument  = new BoundExpression()
                                        {
                                            Definition = foreachLocal,
                                            Instance   = null,
                                        },
                                        Type = this.host.PlatformType.SystemBoolean,
                                    },
                                },
                            },
                        },
                        FinallyBody = new BlockStatement()
                        {
                            Statements = new List <IStatement>()
                            {
                                new ConditionalStatement()
                                {
                                    Condition = new Equality()
                                    {
                                        LeftOperand = new BoundExpression()
                                        {
                                            Definition = foreachLocal, Instance = null, Type = foreachLocal.Type,
                                        },
                                        RightOperand = new CompileTimeConstant()
                                        {
                                            Type = foreachLocal.Type, Value = null,
                                        },
                                        Type = this.host.PlatformType.SystemBoolean,
                                    },
                                    FalseBranch = new EmptyStatement(),
                                    TrueBranch  = new ExpressionStatement()
                                    {
                                        Expression = new MethodCall()
                                        {
                                            Arguments     = new List <IExpression>(),
                                            IsStaticCall  = false,
                                            IsVirtualCall = true,
                                            MethodToCall  = this.disposeMethod,
                                            ThisArgument  = new BoundExpression()
                                            {
                                                Definition = foreachLocal,
                                                Instance   = null,
                                            },
                                            Type = this.host.PlatformType.SystemVoid,
                                        },
                                    },
                                },
                            },
                        },
                    },
                },
            };

            return(result);
        }
Example #40
0
        public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
        {
            ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory;

            ObjectConstructor <object> creatorConstructor = null;

            if (creator != null)
            {
                creatorConstructor = delegateFactory.CreateParameterizedConstructor(creator);
            }
            else
            {
                if (ReflectionUtils.HasDefaultConstructor(t, false))
                {
                    Func <object> ctor = delegateFactory.CreateDefaultConstructor <object>(t);

                    creatorConstructor = (id, args) => ctor();
                }
            }

            ReflectionObject d = new ReflectionObject(creatorConstructor);

            foreach (string memberName in memberNames)
            {
                MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public);
                if (members.Length != 1)
                {
                    throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName));
                }

                MemberInfo member = members.Single();

                ReflectionMember reflectionMember = new ReflectionMember();

                switch (member.MemberType())
                {
                case MemberTypes.Field:
                case MemberTypes.Property:
                    if (ReflectionUtils.CanReadMemberValue(member, false))
                    {
                        reflectionMember.Getter = delegateFactory.CreateGet <object>(member);
                    }

                    if (ReflectionUtils.CanSetMemberValue(member, false, false))
                    {
                        reflectionMember.Setter = delegateFactory.CreateSet <object>(member);
                    }
                    break;

                case MemberTypes.Method:
                    MethodInfo method = (MethodInfo)member;
                    if (method.IsPublic)
                    {
                        ParameterInfo[] parameters = method.GetParameters();
                        if (parameters.Length == 0 && method.ReturnType != typeof(void))
                        {
                            MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method);
                            reflectionMember.Getter = target => call(target);
                        }
                        else if (parameters.Length == 1 && method.ReturnType == typeof(void))
                        {
                            MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method);
                            reflectionMember.Setter = (target, arg) => call(target, arg);
                        }
                    }
                    break;

                default:
                    throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name));
                }

                if (ReflectionUtils.CanReadMemberValue(member, false))
                {
                    reflectionMember.Getter = delegateFactory.CreateGet <object>(member);
                }

                if (ReflectionUtils.CanSetMemberValue(member, false, false))
                {
                    reflectionMember.Setter = delegateFactory.CreateSet <object>(member);
                }

                reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member);

                d.Members[memberName] = reflectionMember;
            }

            return(d);
        }
Example #41
0
        public Mnemonic Get(ASTNode?node)
        {
            Mnemonic result = null;
            var      symbol = node.Value.Symbol.Name;

            switch (symbol)
            {
            case "assigment":
                result = new Assigment(node, this);
                break;

            case "expression":
                result = new Expression(node, this);
                break;

            case "expression_arg":
            case "expression_sum":
            case "expression_mult":
            case "expression_cmp":
            case "expression_bracket":
            case "expression_bool":
                result = new ExpressionCommon(node, this);
                break;

            case "expression_prefix":
                result = new ExpressionPrefix(node, this);
                break;

            case "NUMBER":
                result = new ValueNumber(node);
                break;

            case "STRING":
                result = new ValueString(node);
                break;

            case "method_call":
                result = new MethodCall(node, this);
                break;

            case "emptyLine":
                result = new Nop(node);
                break;

            case "variable_name":
                result = new VariableName(node, this);
                break;

            case "if":
                result = new If(node, this);
                break;

            case "block_of_lopla":
                result = new Block(node, this);
                break;

            case "method":
                result = new MethodDeclaration(node, this);
                break;

            case "declare_table":
                result = new DeclareTable(node, this);
                break;

            case "var_value_table":
                result = new ValueTable(node, this);
                break;

            case "while":
                result = new While(node, this);
                break;

            case "return":
                result = new Return(node, this);
                break;

            default:
                AddError(
                    new CompilationError($"{symbol} not handled by compiler. line: {node?.Position.Line}"));
                break;
            }

            return(result);
        }
Example #42
0
 public override Expression VisitMethodCall(MethodCall call)
 {
     //TODO: add method preconditions to current preconditions
     //TODO: treat arguments as assignment statements
     return(base.VisitMethodCall(call));
 }
        public AfterWrappedMethodDelegate BeforeWrappedMethod(Type type, string methodName, string argumentSignature,
                                                              object invocationTarget, object[] methodArguments, string tracerFactoryName, string metricName,
                                                              uint tracerArguments, ulong functionId)
        {
            InstrumentedMethodInfo instrumentedMethodInfo = default(InstrumentedMethodInfo);
            TrackedWrapper         trackedWrapper;

            if (_functionIdToWrapper.TryGetValue(functionId, out InstrumentedMethodInfoWrapper methodAndWrapper))
            {
                instrumentedMethodInfo = methodAndWrapper.instrumentedMethodInfo;
                trackedWrapper         = methodAndWrapper.wrapper;
            }
            else
            {
                var isAsync = TracerArgument.IsAsync(tracerArguments);

                tracerFactoryName = ResolveTracerFactoryNameForAttributeInstrumentation(tracerArguments, isAsync, tracerFactoryName);

                var method = new Method(type, methodName, argumentSignature, functionId.GetHashCode());
                var transactionNamePriority = TracerArgument.GetTransactionNamingPriority(tracerArguments);
                instrumentedMethodInfo = new InstrumentedMethodInfo((long)functionId, method, tracerFactoryName, isAsync, metricName, transactionNamePriority, TracerArgument.IsFlagSet(tracerArguments, TracerFlags.WebTransaction));

                trackedWrapper = _wrapperMap.Get(instrumentedMethodInfo);

                if (trackedWrapper == null)
                {
                    Log.WarnFormat("WrapperMap.Get unexpectedly returned null for {0}.{1}({2}) in assembly [{3}] (requested wrapper name was {4}).",
                                   instrumentedMethodInfo.Method.Type.FullName,
                                   instrumentedMethodInfo.Method.MethodName,
                                   instrumentedMethodInfo.Method.ParameterTypeNames,
                                   instrumentedMethodInfo.Method.Type.Assembly.FullName,
                                   instrumentedMethodInfo.RequestedWrapperName);

                    return(null);
                }

                _functionIdToWrapper[functionId] = new InstrumentedMethodInfoWrapper(instrumentedMethodInfo, trackedWrapper);
                GenerateLibraryVersionSupportabilityMetric(instrumentedMethodInfo);
            }

            var wrapper = trackedWrapper.Wrapper;

            var transaction = _agent.CurrentTransaction;

            if (Log.IsFinestEnabled)
            {
                transaction.LogFinest($"Attempting to execute {wrapper} found from InstrumentedMethodInfo: {instrumentedMethodInfo}");
            }

            if (transaction.IsFinished)
            {
                if (Log.IsFinestEnabled)
                {
                    if (wrapper.IsTransactionRequired)
                    {
                        transaction.LogFinest($"Transaction has already ended, skipping method {type.FullName}.{methodName}({argumentSignature}).");
                    }
                    else
                    {
                        transaction.LogFinest("Transaction has already ended, detaching from transaction storage context.");
                    }
                }

                transaction.Detach();
                transaction = _agent.CurrentTransaction;

                if (wrapper.IsTransactionRequired)
                {
                    return(Delegates.NoOp);
                }
            }

            if (wrapper.IsTransactionRequired)
            {
                if (!transaction.IsValid)
                {
                    if (Log.IsFinestEnabled)
                    {
                        transaction.LogFinest($"No transaction, skipping method {type.FullName}.{methodName}({argumentSignature})");
                    }

                    return(Delegates.NoOp);
                }

                if (transaction.CurrentSegment.IsLeaf)
                {
                    return(Delegates.NoOp);
                }
            }

            var methodCall             = new MethodCall(instrumentedMethodInfo.Method, invocationTarget, methodArguments);
            var instrumentedMethodCall = new InstrumentedMethodCall(methodCall, instrumentedMethodInfo);

            // if the wrapper throws an exception when executing the pre-method code, make sure the wrapper isn't called again in the future
            try
            {
                using (_agentTimerService.StartNew("BeforeWrappedMethod", type.FullName, methodName))
                {
                    var afterWrappedMethod = wrapper.BeforeWrappedMethod(instrumentedMethodCall, _agent, transaction);
                    return((result, exception) =>
                    {
                        using (_agentTimerService.StartNew("AfterWrappedMethod", type.FullName, methodName))
                        {
                            // if the wrapper throws an exception when executing the post-method code, make sure the wrapper isn't called again in the future
                            try
                            {
                                afterWrappedMethod(result, exception);
                                trackedWrapper.NoticeSuccess();
                            }
                            catch (Exception)
                            {
                                HandleBeforeWrappedMethodException(functionId, trackedWrapper, instrumentedMethodCall, instrumentedMethodInfo);
                                throw;
                            }
                        }
                    });
                }
            }
            catch
            {
                HandleBeforeWrappedMethodException(functionId, trackedWrapper, instrumentedMethodCall, instrumentedMethodInfo);
                throw;
            }
        }
Example #44
0
 /// <summary cref="IValueVisitor.Visit(MethodCall)"/>
 public void Visit(MethodCall methodCall) =>
 CodeGenerator.GenerateCode(methodCall);
Example #45
0
        private Expression _PrimaryExpression()
        {
            if (Current.TokenKind == TokenKind.StringStart)
            {
                return(_ReadString());
            }
            else if (Current.TokenKind == TokenKind.ID)
            {
                Token id = _Consume();

                Expression exp = null;

                // if ( follows ID, we have a function call
                if (Current.TokenKind == TokenKind.LParen)
                {
                    _Consume();                         // consume LParen
                    Expression[] args = _ReadArguments();
                    _Consume(TokenKind.RParen);

                    exp = new FCall(id.Line, id.Col, id.Data, args);
                }
                else                  // else, we just have id
                {
                    exp = new Name(id.Line, id.Col, id.Data);
                }

                // while we have ".", keep chaining up field access or method call
                while (Current.TokenKind == TokenKind.Dot || Current.TokenKind == TokenKind.LBracket)
                {
                    if (Current.TokenKind == TokenKind.Dot)
                    {
                        _Consume();                             // consume DOT
                        Token field = _Consume(TokenKind.ID);   // consume ID after dot

                        // if "(" after ID, then it's a method call
                        if (Current.TokenKind == TokenKind.LParen)
                        {
                            _Consume();                             // consume "("
                            Expression[] args = _ReadArguments();
                            _Consume(TokenKind.RParen);             // read ")"

                            exp = new MethodCall(field.Line, field.Col, exp, field.Data, args);
                        }
                        else
                        {
                            exp = new FieldAccess(field.Line, field.Col, exp, field.Data);
                        }
                    }
                    else                     // must be LBracket
                    {
                        // array access
                        Token bracket = Current;
                        _Consume();                         // consume [
                        Expression indexExp = _TopExpression();
                        _Consume(TokenKind.RBracket);

                        exp = new ArrayAccess(bracket.Line, bracket.Col, exp, indexExp);
                    }
                }

                return(exp);
            }
            else if (Current.TokenKind == TokenKind.Integer)
            {
                int        value      = Int32.Parse(Current.Data);
                IntLiteral intLiteral = new IntLiteral(Current.Line, Current.Col, value);
                _Consume();                 // consume int
                return(intLiteral);
            }
            else if (Current.TokenKind == TokenKind.Double)
            {
                double        value    = Double.Parse(Current.Data);
                DoubleLiteral dLiteral = new DoubleLiteral(Current.Line, Current.Col, value);
                _Consume();                 // consume int
                return(dLiteral);
            }
            else if (Current.TokenKind == TokenKind.LParen)
            {
                _Consume();                 // eat (
                Expression exp = _TopExpression();
                _Consume(TokenKind.RParen); // eat )

                return(exp);
            }
            else
            {
                throw new ParseException("意外的 Token 表达式:" + Current.TokenKind + "。Token类型 即非 ID 也非 string。", Current.Line, Current.Col);
            }
        }
Example #46
0
        public void MethodCall_Created_With_Factory_Should_Be_Receive()
        {
            var methodCall = MethodCall.Receive();

            Assert.True(methodCall.IsReceiveHandlerCall);
        }
        void RegisterEventHandler(MethodCall node, object component)
        {
            string eventHandlerName = GetEventHandlerName(node);

            RegisterEventHandler(component, node.MethodName, eventHandlerName);
        }
Example #48
0
 public FSharpFunction(object?instance, MethodCall <object?, object> invoker)
 {
     _instance = instance;
     _invoker  = invoker;
 }
Example #49
0
        private System.Type TypeOfExpr(Expr expr)
        {
            if (expr is StringLiteral)
            {
                return(typeof(string));
            }
            else if (expr is IntLiteral)
            {
                return(typeof(int));
            }
            else if (expr is BinExpr)
            {
                return(TypeOfExpr(((BinExpr)expr).Right));
            }

            else if (expr is Variable)
            {
                Variable var = (Variable)expr;
                if (this.symbolTable.ContainsKey(var.Ident))
                {
                    Emit.LocalBuilder locb = this.symbolTable[var.Ident];
                    return(locb.LocalType);
                }
                else if (this.parameterTable.ContainsKey(var.Ident))
                {
                    return(this.parameterTable[var.Ident]);
                }
                else if (this.typefieldList.ContainsKey(var.Ident))
                {
                    return(this.typefieldList[var.Ident].FieldType);
                }

                else
                {
                    throw new System.Exception("undeclared variable '" + var.Ident + "'");
                }
            }
            else if (expr is MethodCall)
            {
                MethodCall callMethod = (MethodCall)expr;
                if (callMethod.returnType == null)
                {
                    if (!callMethod.IsConstrutor)
                    {
                        callMethod.returnType = ((MethodInfo)GetMethodInfo(callMethod)).ReturnParameter.ParameterType;
                    }
                    else
                    {
                        callMethod.returnType = ((System.Reflection.MemberInfo)GetMethodInfo(callMethod)).ReflectedType;
                    }

                    //   typefieldList = typeof(void);
                    // callMethod.returnType = ((ConstructorInfo)GetMethodInfo(callMethod)).ReturnParameter.ParameterType;
                }

                return(callMethod.returnType);
            }

            else
            {
                throw new System.Exception("don't know how to calculate the type of " + expr.GetType().Name);
            }
        }
Example #50
0
 /// <inheritdoc />
 public IFilterFactory <T> NotEquals <TValue>(Expression <Func <T, object> > propertySelector, MethodCall value)
 {
     _documentQuery.WhereNotEquals(GetFieldName(propertySelector), value);
     return(this);
 }
Example #51
0
    private void AddFactoryMethodArguments(
        MethodInfo factory,
        MethodCall factoryMethodCall,
        List <ApiCall> quotedValues)
    {
        foreach (var factoryMethodParameter in factory.GetParameters())
        {
            var parameterName = factoryMethodParameter.Name;
            var parameterType = factoryMethodParameter.ParameterType;

            ApiCall quotedCodeBlock = FindValue(parameterName, quotedValues);

            // if we have Block(List<StatementSyntax>(new StatementSyntax[] { A, B })), just simplify it to
            // Block(A, B)
            if (quotedCodeBlock != null && factory.GetParameters().Length == 1 && factoryMethodParameter.GetCustomAttribute <ParamArrayAttribute>() != null)
            {
                var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall;
                if (methodCall != null && methodCall.Name.Contains("List") && methodCall.Arguments.Count == 1)
                {
                    var argument      = methodCall.Arguments[0] as ApiCall;
                    var arrayCreation = argument.FactoryMethodCall as MethodCall;
                    if (argument != null && arrayCreation != null && arrayCreation.Name.StartsWith("new ") && arrayCreation.Name.EndsWith("[]"))
                    {
                        foreach (var arrayElement in arrayCreation.Arguments)
                        {
                            factoryMethodCall.AddArgument(arrayElement);
                        }

                        quotedValues.Remove(quotedCodeBlock);
                        return;
                    }
                }
            }

            // special case to prefer SyntaxFactory.IdentifierName("C") to
            // SyntaxFactory.IdentifierName(Syntax.Identifier("C"))
            if (parameterName == "name" && parameterType == typeof(string))
            {
                quotedCodeBlock = quotedValues.First(a => a.Name == "Identifier");
                var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall;
                if (methodCall != null && methodCall.Name == SyntaxFactoryMethod("Identifier"))
                {
                    if (methodCall.Arguments.Count == 1)
                    {
                        factoryMethodCall.AddArgument(methodCall.Arguments[0]);
                    }
                    else
                    {
                        factoryMethodCall.AddArgument(quotedCodeBlock);
                    }

                    quotedValues.Remove(quotedCodeBlock);
                    continue;
                }
            }

            // special case to prefer SyntaxFactory.ClassDeclarationSyntax(string) instead of
            // SyntaxFactory.ClassDeclarationSyntax(SyntaxToken)
            if (parameterName == "identifier" && parameterType == typeof(string))
            {
                var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall;
                if (methodCall != null &&
                    methodCall.Name == SyntaxFactoryMethod("Identifier") &&
                    methodCall.Arguments.Count == 1)
                {
                    factoryMethodCall.AddArgument(methodCall.Arguments[0]);
                    quotedValues.Remove(quotedCodeBlock);
                    continue;
                }
            }

            if (quotedCodeBlock != null)
            {
                factoryMethodCall.AddArgument(quotedCodeBlock);
                quotedValues.Remove(quotedCodeBlock);
            }
            else if (!factoryMethodParameter.IsOptional)
            {
                if (parameterType.IsArray)
                {
                    // assuming this is a params parameter that accepts an array, so if we have nothing we don't need to pass anything
                    continue;
                }

                throw new InvalidOperationException(
                          string.Format(
                              "Couldn't find value for parameter '{0}' of method '{1}'. Go to QuotePropertyValues() and add your node type to the exception list.",
                              parameterName,
                              factory));
            }
        }
    }
Example #52
0
        public void MethodCall_To_Receive_Should_Be_Receive()
        {
            var methodCall = new MethodCall("Receive");

            Assert.True(methodCall.IsReceiveHandlerCall);
        }
Example #53
0
 public ApiCall(string name, MethodCall factoryMethodCall)
 {
     Name = name;
     FactoryMethodCall = factoryMethodCall;
 }
Example #54
0
        public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
        {
            MemberInfo                 memberInfo;
            ReflectionMember           reflectionMember;
            MemberTypes                memberType;
            ReflectionDelegateFactory  reflectionDelegateFactory = JsonTypeReflector.ReflectionDelegateFactory;
            ObjectConstructor <object> objectConstructor         = null;

            if (creator != null)
            {
                objectConstructor = reflectionDelegateFactory.CreateParameterizedConstructor(creator);
            }
            else if (ReflectionUtils.HasDefaultConstructor(t, false))
            {
                Func <object> func = reflectionDelegateFactory.CreateDefaultConstructor <object>(t);
                objectConstructor = (object[] args) => func();
            }
            ReflectionObject reflectionObject = new ReflectionObject(objectConstructor);

            string[] strArrays = memberNames;
            for (int i = 0; i < (int)strArrays.Length; i++)
            {
                string       str    = strArrays[i];
                MemberInfo[] member = t.GetMember(str, BindingFlags.Instance | BindingFlags.Public);
                if ((int)member.Length != 1)
                {
                    throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, str));
                }
                memberInfo       = ((IEnumerable <MemberInfo>)member).Single <MemberInfo>();
                reflectionMember = new ReflectionMember();
                memberType       = memberInfo.MemberType();
                if (memberType != MemberTypes.Field)
                {
                    if (memberType != MemberTypes.Method)
                    {
                        goto Label1;
                    }
                    MethodInfo methodInfo = (MethodInfo)memberInfo;
                    if (methodInfo.IsPublic)
                    {
                        ParameterInfo[] parameters = methodInfo.GetParameters();
                        if (parameters.Length == 0 && methodInfo.ReturnType != typeof(void))
                        {
                            MethodCall <object, object> methodCall = reflectionDelegateFactory.CreateMethodCall <object>(methodInfo);
                            reflectionMember.Getter = (object target) => methodCall(target, new object[0]);
                        }
                        else if ((int)parameters.Length == 1 && methodInfo.ReturnType == typeof(void))
                        {
                            MethodCall <object, object> methodCall1 = reflectionDelegateFactory.CreateMethodCall <object>(methodInfo);
                            reflectionMember.Setter = (object target, object arg) => methodCall1(target, new object[] { arg });
                        }
                    }
                }
                else
                {
                    goto Label0;
                }
Label2:
                if (ReflectionUtils.CanReadMemberValue(memberInfo, false))
                {
                    reflectionMember.Getter = reflectionDelegateFactory.CreateGet <object>(memberInfo);
                }
                if (ReflectionUtils.CanSetMemberValue(memberInfo, false, false))
                {
                    reflectionMember.Setter = reflectionDelegateFactory.CreateSet <object>(memberInfo);
                }
                reflectionMember.MemberType   = ReflectionUtils.GetMemberUnderlyingType(memberInfo);
                reflectionObject.Members[str] = reflectionMember;
            }
            return(reflectionObject);

Label0:
            if (ReflectionUtils.CanReadMemberValue(memberInfo, false))
            {
                reflectionMember.Getter = reflectionDelegateFactory.CreateGet <object>(memberInfo);
            }
            if (ReflectionUtils.CanSetMemberValue(memberInfo, false, false))
            {
                reflectionMember.Setter = reflectionDelegateFactory.CreateSet <object>(memberInfo);
                goto Label2;
            }
            else
            {
                goto Label2;
            }
Label1:
            if (memberType != MemberTypes.Property)
            {
                throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, memberInfo.MemberType(), memberInfo.Name));
            }
            goto Label0;
        }
Example #55
0
 public static void SetServerIdentity(MethodCall m, object srvID)
 {
     ((IInternalMessage)m).ServerIdentityObject = (ServerIdentity)srvID;
 }
Example #56
0
 public override string ToString()
 {
     return(MethodCall.ToString());
 }
Example #57
0
 /// <inheritdoc />
 public IFilterFactory <T> NotEquals(string fieldName, MethodCall value)
 {
     _documentQuery.WhereNotEquals(fieldName, (object)value);
     return(this);
 }
Example #58
0
    private static void Print(
        MemberCall call,
        StringBuilder sb,
        int depth,
        bool openParenthesisOnNewLine       = false,
        bool closingParenthesisOnNewLine    = false,
        bool useCurliesInsteadOfParentheses = false)
    {
        var openParen  = useCurliesInsteadOfParentheses ? "{" : "(";
        var closeParen = useCurliesInsteadOfParentheses ? "}" : ")";

        Print(call.Name, sb, depth);

        MethodCall methodCall = call as MethodCall;

        if (methodCall != null)
        {
            if (methodCall.Arguments == null || !methodCall.Arguments.Any())
            {
                Print(openParen + closeParen, sb, 0);
                return;
            }

            if (openParenthesisOnNewLine)
            {
                PrintNewLine(sb);
                Print(openParen, sb, depth);
            }
            else
            {
                Print(openParen, sb, 0);
            }

            PrintNewLine(sb);

            bool needComma = false;
            foreach (var block in methodCall.Arguments)
            {
                if (needComma)
                {
                    Print(",", sb, 0);
                    PrintNewLine(sb);
                }

                if (block is string)
                {
                    Print(
                        (string)block,
                        sb,
                        depth + 1);
                }
                else if (block is SyntaxKind)
                {
                    Print("SyntaxKind." + ((SyntaxKind)block).ToString(), sb, depth + 1);
                }
                else if (block is ApiCall)
                {
                    Print(
                        block as ApiCall,
                        sb,
                        depth + 1,
                        openParenthesisOnNewLine: openParenthesisOnNewLine,
                        closingParenthesisOnNewLine: closingParenthesisOnNewLine);
                }

                needComma = true;
            }

            if (closingParenthesisOnNewLine)
            {
                PrintNewLine(sb);
                Print(closeParen, sb, depth);
            }
            else
            {
                Print(closeParen, sb, 0);
            }
        }
    }
Example #59
0
        public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
        {
            ReflectionObject          obj2 = new ReflectionObject();
            ReflectionDelegateFactory reflectionDelegateFactory = JsonTypeReflector.ReflectionDelegateFactory;

            if (creator != null)
            {
                obj2.Creator = reflectionDelegateFactory.CreateParameterizedConstructor(creator);
            }
            else if (ReflectionUtils.HasDefaultConstructor(t, false))
            {
                Func <object> ctor = reflectionDelegateFactory.CreateDefaultConstructor <object>(t);
                obj2.Creator = args => ctor();
            }
            foreach (string str in memberNames)
            {
                MethodInfo   info2;
                MemberInfo[] source = t.GetMember(str, BindingFlags.Public | BindingFlags.Instance);
                if (source.Length != 1)
                {
                    throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, str));
                }
                MemberInfo       memberInfo = source.Single <MemberInfo>();
                ReflectionMember member     = new ReflectionMember();
                MemberTypes      types      = memberInfo.MemberType();
                if (types != MemberTypes.Field)
                {
                    if (types == MemberTypes.Method)
                    {
                        goto Label_0107;
                    }
                    if (types != MemberTypes.Property)
                    {
                        throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, memberInfo.MemberType(), memberInfo.Name));
                    }
                }
                if (ReflectionUtils.CanReadMemberValue(memberInfo, false))
                {
                    member.Getter = reflectionDelegateFactory.CreateGet <object>(memberInfo);
                }
                if (ReflectionUtils.CanSetMemberValue(memberInfo, false, false))
                {
                    member.Setter = reflectionDelegateFactory.CreateSet <object>(memberInfo);
                }
                goto Label_01F3;
Label_0107:
                info2 = (MethodInfo)memberInfo;
                if (info2.IsPublic)
                {
                    ParameterInfo[] parameters = info2.GetParameters();
                    if ((parameters.Length == 0) && (info2.ReturnType != typeof(void)))
                    {
                        MethodCall <object, object> call = reflectionDelegateFactory.CreateMethodCall <object>(info2);
                        member.Getter = target => call(target, new object[0]);
                    }
                    else if ((parameters.Length == 1) && (info2.ReturnType == typeof(void)))
                    {
                        MethodCall <object, object> call1 = reflectionDelegateFactory.CreateMethodCall <object>(info2);
                        member.Setter = delegate(object target, object arg) {
                            object[] args = new object[] { arg };
                            call1(target, args);
                        };
                    }
                }
Label_01F3:
                if (ReflectionUtils.CanReadMemberValue(memberInfo, false))
                {
                    member.Getter = reflectionDelegateFactory.CreateGet <object>(memberInfo);
                }
                if (ReflectionUtils.CanSetMemberValue(memberInfo, false, false))
                {
                    member.Setter = reflectionDelegateFactory.CreateSet <object>(memberInfo);
                }
                member.MemberType = ReflectionUtils.GetMemberUnderlyingType(memberInfo);
                obj2.Members[str] = member;
            }
            return(obj2);
        }
Example #60
0
        private void ControlInvoke(object sender, EventArgs e)
        {
            MethodCall methodCall = (MethodCall)argumentInvokeList.Dequeue();

            methodCall.invoker(methodCall.arguments);
        }