public object ChangeReturnValue(MethodInvocation call) { int res = (int)call.Proceed(); res++; return res; }
public object MyAroundInterceptor(MethodInvocation call) { Console.WriteLine("before"); object res = call.Proceed(); Console.WriteLine("after"); return res; }
/// <inheritdoc /> public IMethodReturn Invoke(MethodInvocation methodInvocation) { var methodName = String.Format("{0}.{1}({2})", methodInvocation.Target.GetType(), methodInvocation.MethodBase.Name, methodInvocation.Parameters.Aggregate("", (ag, p) => ag + (ag != "" ? ", " : "") + (p.Value != null ? p.ToString() : "<null>"))); if (methodInvocation.IsInvoked) { _trace.Warn("Interception." + Name, String.Format("Unable to profile {0} as method is already executed! " + "Please check your interception behavior configuration", methodName)); return(methodInvocation.Return); } var methodBase = TypeHelper.GetMethodBySign(methodInvocation.Target.GetType(), methodInvocation.MethodBase, methodInvocation.GenericTypes.ToArray()); var sw = new Stopwatch(); sw.Start(); var result = methodBase.Invoke(methodInvocation.Target, methodInvocation.Parameters.Values.ToArray()); sw.Stop(); _trace.Debug("interception." + Name, "{0}: {1} ms", methodName, sw.ElapsedMilliseconds.ToString()); methodInvocation.IsInvoked = true; return(methodInvocation.Return = new MethodReturn(result)); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var token = root.FindToken(diagnostic.Location.SourceSpan.Start); var expression = token.Parent.FindNearestContainer <InvocationExpressionSyntax, ObjectCreationExpressionSyntax>(); if (expression != null) { if (expression is ObjectCreationExpressionSyntax creationExpression) { if (creationExpression.ArgumentList?.Arguments.Count == 1) { var invocation = new ConstructorInvocation(creationExpression); context.RegisterCodeFix(CodeAction.Create(title: "Generate splatting with value parameters", createChangedDocument: c => GenerateSplatting(context.Document, invocation, false, c), equivalenceKey: "Generate splatting with value parameters" + "_constructor"), diagnostic); context.RegisterCodeFix(CodeAction.Create(title: "Generate splatting with named parameters", createChangedDocument: c => GenerateSplatting(context.Document, invocation, true, c), equivalenceKey: "Generate splatting with named parameters" + "_constructor"), diagnostic); } } else if (expression is InvocationExpressionSyntax invocationExpression) { if (invocationExpression.ArgumentList?.Arguments.Count == 1) { var invocation = new MethodInvocation(invocationExpression); context.RegisterCodeFix(CodeAction.Create(title: "Generate splatting with value parameters", createChangedDocument: c => GenerateSplatting(context.Document, invocation, false, c), equivalenceKey: "Generate splatting with value parameters"), diagnostic); context.RegisterCodeFix(CodeAction.Create(title: "Generate splatting with named parameters", createChangedDocument: c => GenerateSplatting(context.Document, invocation, true, c), equivalenceKey: "Generate splatting with named parameters"), diagnostic); } } } }
public object HandleCall(MethodInvocation call) { IProxy proxy = (IProxy)call.Target; InterceptedParameter stateParam = (InterceptedParameter)call.Parameters [0]; IContext ctx = (IContext)stateParam.Value; proxy.SetInterceptor(ctx.Interceptor); if (proxy.GetInterceptor() == null) { call.Proceed(); return(null); } else { bool cancel = false; proxy.GetInterceptor().NotifyInstantiatingObject(call.Target, ref cancel); if (!cancel) { call.Proceed(); } proxy.GetInterceptor().NotifyInstantiatedObject(call.Target); return(null); } }
public object HandleCall(MethodInvocation call) { ParameterInfo[] parameters =call.Method.GetParameters(); int i=0; //validate each DBC attribute for each parameter foreach (ParameterInfo parameter in parameters) { InterceptedParameter interceptedParameter = (InterceptedParameter)call.Parameters[i]; object[] parameterAttributes = parameter.GetCustomAttributes(typeof(DbCAttribute),true); foreach (DbCAttribute attribute in parameterAttributes) { attribute.Validate(interceptedParameter.Name,interceptedParameter.Value) ; } i++; } object result = call.Proceed() ; object[] methodAttributes = call.Method.GetCustomAttributes(typeof(DbCAttribute),true); foreach (DbCAttribute attribute in methodAttributes) { attribute.Validate("@result",result) ; } return result; }
int ICalculator.Add(int x, int y) { var method = this.GetInterfaceMethod <Func <int, int, int>, ICalculator>(((ICalculator)this).Add); var invocation = new MethodInvocation(this, method, x, y); var returns = pipeline.Invoke( invocation, (input, next) => { try { var returnValue = calculator != null ? calculator.Add(x, y) : default(int); return(input.CreateValueReturn(returnValue, x, y)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } return(((int?)returns.ReturnValue).GetValueOrDefault()); }
public void Intercept (IInvocation invocation) { if (invocation.Method.DeclaringType == typeof (IProxy)) { invocation.ReturnValue = Behaviors; return; } var input = new MethodInvocation(invocation.InvocationTarget, invocation.Method, invocation.Arguments); var returns = pipeline.Invoke(input, (i, next) => { try { invocation.Proceed(); var returnValue = invocation.ReturnValue; return input.CreateValueReturn(returnValue, invocation.Arguments); } catch (Exception ex) { return input.CreateExceptionReturn(ex); } }); var exception = returns.Exception; if (exception != null) throw exception; invocation.ReturnValue = returns.ReturnValue; for (int i = 0; i < returns.Outputs.Count; i++) { var name = returns.Outputs.GetName(i); var index = input.Arguments.IndexOf (name); invocation.SetArgumentValue (index, returns.Outputs[index]); } }
private object HandleSetProperty(MethodInvocation call) { IProxy proxy = (IProxy) call.Target; bool cancel = false; object value = ((InterceptedParameter)call.Parameters[0]).Value; string propertyName = call.Method.Name.Substring(4); object refValue = value; #if NET2 IPropertyChangedHelper propertyChangedObj = (IPropertyChangedHelper)proxy; propertyChangedObj.OnPropertyChanging (propertyName); #endif Puzzle.NPersist.Framework.Interfaces.IInterceptor interceptor = proxy.GetInterceptor(); if (interceptor != null) { interceptor.NotifyPropertySet(call.Target, propertyName, ref refValue, ref cancel); } if (cancel) { return null; } IContext context = null; if (interceptor != null) { context = interceptor.Context; } object oldValue = null; if (context != null) oldValue = context.ObjectManager.GetPropertyValue(call.ExecutionTarget, propertyName); else oldValue = call.ExecutionTarget.GetType().GetProperty(propertyName).GetValue(call.ExecutionTarget, null); ((InterceptedParameter)call.Parameters[0]).Value = refValue; call.Proceed(); #if NET2 propertyChangedObj.OnPropertyChanged (propertyName); #endif if (interceptor != null) { interceptor.NotifyWroteProperty(call.Target, propertyName, refValue, oldValue); } return null; }
void IDisposable.Dispose() { var method = this.GetInterfaceMethod <Action, ICalculator>(((ICalculator)this).TurnOn); var invocation = new MethodInvocation(this, method); var returns = pipeline.Invoke( invocation, (input, next) => { try { if (disposable != null) { disposable.Dispose(); } return(input.CreateValueReturn(null)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } }
private object NamedFactoryCall(MethodInvocation call, FactoryMethodAttribute attrib,IContext context) { string factoryId = GetFactoryId(call, attrib); //get from context cache if (attrib.InstanceMode == InstanceMode.PerContext && context.State.namedPerContextObjects.ContainsKey(factoryId)) return context.State.namedPerContextObjects[factoryId]; //get from graph cache if (attrib.InstanceMode == InstanceMode.PerGraph && context.State.namedPerGraphObjects.ContainsKey(factoryId)) return context.State.namedPerGraphObjects[factoryId]; //get from thread cache if (attrib.InstanceMode == InstanceMode.PerThread && context.State.namedPerThreadObjects.ContainsKey(factoryId)) return context.State.namedPerThreadObjects[factoryId]; object res = call.Proceed(); if (res is IRunnable) RunnableEngine.RunRunnable(res as IRunnable); //add to context cache if (attrib.InstanceMode == InstanceMode.PerContext) context.State.namedPerContextObjects.Add(factoryId, res); //add to graph cache if (attrib.InstanceMode == InstanceMode.PerGraph) context.State.namedPerGraphObjects.Add(factoryId, res); //add to thread cache if (attrib.InstanceMode == InstanceMode.PerThread) context.State.namedPerThreadObjects.Add(factoryId, res); return res; }
private object HandleGetProperty(MethodInvocation call) { IProxy proxy = (IProxy)call.Target; string propertyName = call.Method.Name.Substring(4); //object value = call.Proceed(); object value = null; bool cancel = false; Puzzle.NPersist.Framework.Interfaces.IInterceptor interceptor = proxy.GetInterceptor(); if (interceptor != null) { interceptor.NotifyPropertyGet(call.Target, propertyName, ref value, ref cancel); } if (cancel) { return(value); } //if (cancel) {return GetDefaultValue(call.ReturnType);} value = call.Proceed(); if (interceptor != null) { interceptor.NotifyReadProperty(proxy, propertyName, ref value); } return(value); }
public string Visit(MethodInvocation methodInvocation) { return(String.Format("{0}.{1}({2})", Translate(methodInvocation.Instance), Translate(methodInvocation.MethodName), Translate(methodInvocation.Arguments, ", "))); }
public void DoesNotFailWithNonMethodInfo() { var ctor = typeof(Foo).GetConstructors().First(); IAvatarBehavior behavior = new DefaultValueBehavior(); behavior.Execute(MethodInvocation.Create(new object(), ctor, PlatformID.Win32NT), null !); }
/// <summary> /// JoinPointが呼び出されると、このメソッドが割り込みます /// </summary> /// <param name="invocation">呼び出されたメソッド</param> /// <param name="outArguments">メソッドのout引数</param> /// <returns>メソッドの戻り値</returns> public object Invoke(MethodInvocation invocation, out object[] outArguments) { InvariantConditionAttribute invariantCondition = (InvariantConditionAttribute)Attribute.GetCustomAttribute (invocation.Target.GetType(), typeof(InvariantConditionAttribute), true); PreConditionAttribute preCondition = (PreConditionAttribute)Attribute.GetCustomAttribute (invocation.Message.MethodBase, typeof(PreConditionAttribute), true); PostConditionAttribute postCondition = (PostConditionAttribute)Attribute.GetCustomAttribute (invocation.Message.MethodBase, typeof(PostConditionAttribute), true); if (invariantCondition != null) { Debug.Assert(invariantCondition.CheckConstraint(invocation)); } if (preCondition != null) { Debug.Assert(preCondition.CheckConstraint(invocation)); } object ret = invocation.Proceed(out outArguments); if (postCondition != null) { Debug.Assert(postCondition.CheckConstraint(invocation, ret, outArguments)); } if (invariantCondition != null) { Debug.Assert(invariantCondition.CheckConstraint(invocation)); } return(ret); }
public object ChangeReturnValue(MethodInvocation call) { int res = (int)call.Proceed(); res++; return(res); }
public object HandleCall(MethodInvocation call) { ParameterInfo[] parameters = call.Method.GetParameters(); int i = 0; //validate each DBC attribute for each parameter foreach (ParameterInfo parameter in parameters) { InterceptedParameter interceptedParameter = (InterceptedParameter)call.Parameters[i]; object[] parameterAttributes = parameter.GetCustomAttributes(typeof(DbCAttribute), true); foreach (DbCAttribute attribute in parameterAttributes) { attribute.Validate(interceptedParameter.Name, interceptedParameter.Value); } i++; } object result = call.Proceed(); object[] methodAttributes = call.Method.GetCustomAttributes(typeof(DbCAttribute), true); foreach (DbCAttribute attribute in methodAttributes) { attribute.Validate("@result", result); } return(result); }
public object Intercept (InvocationInfo invocation) { //ReturnValue = invocation.TargetMethod.Invoke (invocation.Target, invocation.Arguments); if (invocation.TargetMethod.DeclaringType == typeof (IProxy)) return Behaviors; var input = new MethodInvocation(invocation.Target, invocation.TargetMethod, invocation.Arguments); var returns = pipeline.Invoke(input, (i, next) => { try { var returnValue = invocation.TargetMethod.Invoke (invocation.Target, invocation.Arguments); return input.CreateValueReturn(returnValue, invocation.Arguments); } catch (TargetInvocationException tie) { return input.CreateExceptionReturn(tie.InnerException); } catch (Exception ex) { return input.CreateExceptionReturn(ex); } }); var exception = returns.Exception; if (exception != null) throw exception; for (int i = 0; i < returns.Outputs.Count; i++) { var name = returns.Outputs.GetName(i); var index = input.Arguments.IndexOf (name); invocation.SetArgument (index, returns.Outputs[index]); } return returns.ReturnValue; }
public object HandleCall(MethodInvocation call) { IProxy proxy = (IProxy) call.Target; InterceptedParameter stateParam = (InterceptedParameter) call.Parameters [0]; IContext ctx = (IContext)stateParam.Value; proxy.SetInterceptor(ctx.Interceptor) ; if (proxy.GetInterceptor() == null) { call.Proceed(); return null; } else { bool cancel = false; proxy.GetInterceptor().NotifyInstantiatingObject(call.Target,ref cancel) ; if (!cancel) call.Proceed() ; proxy.GetInterceptor().NotifyInstantiatedObject(call.Target) ; return null; } }
public async Task ProcessAsync() { // Arrange var job = new Job( InvocationData.Serialize( MethodInvocation.FromExpression(() => Method())).Serialize()); var mockFetchedJob = Mock.Get(Mock.Of <IFetchedJob>(fj => fj.JobId == 42)); _mockStorageConnection .Setup(m => m.FetchNextJobAsync()) .ReturnsAsync(mockFetchedJob.Object).Verifiable(); _mockStorageConnection .Setup(m => m.GetJobAsync(42)) .ReturnsAsync(job).Verifiable(); var fixture = Create(); // Act await fixture.ProcessAsync(_context); // Assert _mockStorageConnection.VerifyAll(); _mockStateChanger.Verify(m => m.ChangeState(job, It.IsAny <SucceededState>(), It.IsAny <IStorageTransaction>())); mockFetchedJob.Verify(m => m.Requeue(), Times.Never); mockFetchedJob.Verify(m => m.RemoveFromQueue()); }
public object HandleCall(MethodInvocation call) { int res = (int)call.Proceed(); res++; return(res); }
public object HandleCall(MethodInvocation call) { int res = (int)call.Proceed(); res ++; return res; }
public object HandleCall(MethodInvocation call) { object res = call.Proceed() ; SomeClassWithExplicitIFace some = (SomeClassWithExplicitIFace) res; some.SomeLongProp = 1234; return some; }
public void ValidateAsyncTaskMethodOutput() { const string expectedResult = "Echo Me!"; var boundObject = new AsyncBoundObject(); var objectRepository = new JavascriptObjectRepository(); objectRepository.Register("testObject", boundObject, true, new BindingOptions { CamelCaseJavascriptNames = false }); var methodInvocation = new MethodInvocation(1, 1, 1, nameof(boundObject.AsyncWaitTwoSeconds), 1); methodInvocation.Parameters.Add(expectedResult); var methodRunnerQueue = new ConcurrentMethodRunnerQueue(objectRepository); var manualResetEvent = new ManualResetEvent(false); var actualResult = ""; methodRunnerQueue.MethodInvocationComplete += (sender, args) => { methodRunnerQueue.Stop(); actualResult = args.Result.Result.ToString(); manualResetEvent.Set(); }; methodRunnerQueue.Start(); methodRunnerQueue.Enqueue(methodInvocation); manualResetEvent.WaitOne(3000); Assert.Equal(expectedResult, actualResult); }
public object HandleCall(MethodInvocation call) { object res = call.Proceed(); res = 1000; return(res); }
private void WriteParameters(MethodInvocation action, StringBuilder builder) { foreach (var parameter in action.MethodParameters) { WriteParameter(builder, parameter); } }
public async Task ProcessAsync_Exception() { // Arrange var job = new Job( InvocationData.Serialize( MethodInvocation.FromExpression(() => Throw())).Serialize()); var mockFetchedJob = Mock.Get(Mock.Of <IFetchedJob>(fj => fj.JobId == 42)); _mockStorageConnection .Setup(m => m.FetchNextJobAsync()) .ReturnsAsync(mockFetchedJob.Object); _mockStorageConnection .Setup(m => m.GetJobAsync(42)) .ReturnsAsync(job); _mockStateChanger.Setup(m => m.ChangeState(job, It.IsAny <IState>(), It.IsAny <IStorageTransaction>())) .Throws <Exception>(); var fixture = Create(); // Act await fixture.ProcessAsync(_context); // Assert job.Retries.Should().Be(0); mockFetchedJob.Verify(m => m.Requeue()); }
public async Task ProcessAsync_JobThrows_WithNoRetry() { // Arrange var job = new Job( InvocationData.Serialize( MethodInvocation.FromExpression <NoRetryJob>(j => j.Throw())).Serialize()); var mockFetchedJob = Mock.Get(Mock.Of <IFetchedJob>(fj => fj.JobId == 42)); _mockStorageConnection .Setup(m => m.FetchNextJobAsync()) .ReturnsAsync(mockFetchedJob.Object); _mockStorageConnection .Setup(m => m.GetJobAsync(42)) .ReturnsAsync(job); var fixture = Create(); // Act await fixture.ProcessAsync(_context); // Assert _mockStateChanger.Verify(m => m.ChangeState(job, It.IsAny <FailedState>(), It.IsAny <IStorageTransaction>())); }
Expression DecodeParseString(Expression exp) { while ((_opCode = ReadByte()) != 0xFF) { switch (_opCode & 0xF) { case 0: // SO_AT var x = GetVarOrDirectWord(OpCodeParameter.Param1); var y = GetVarOrDirectWord(OpCodeParameter.Param2); exp = new MethodInvocation(new MemberAccess(exp, "At")).AddArguments(x, y); break; case 1: // SO_COLOR var color = GetVarOrDirectByte(OpCodeParameter.Param1); exp = new MethodInvocation(new MemberAccess(exp, "Color")).AddArguments(color); break; case 2: // SO_CLIPPED var clipped = GetVarOrDirectWord(OpCodeParameter.Param1); exp = new MethodInvocation(new MemberAccess(exp, "Clipped")).AddArguments(clipped); break; case 4: // SO_CENTER exp = new MethodInvocation(new MemberAccess(exp, "Center")); break; case 6: // SO_LEFT var args = new List<Expression>(); if (Game.Version == 3) { args.Add(GetVarOrDirectWord(OpCodeParameter.Param1)); } exp = new MethodInvocation(new MemberAccess(exp, "Left")).AddArguments(args); break; case 7: // SO_OVERHEAD exp = new MethodInvocation(new MemberAccess(exp, "Overhead")); break; case 8: { // SO_SAY_VOICE var offset = GetVarOrDirectWord(OpCodeParameter.Param1); var delay = GetVarOrDirectWord(OpCodeParameter.Param2); exp = new MethodInvocation(new MemberAccess(exp, "PlayCDTrack")).AddArguments(offset, delay); } break; case 15: { // SO_TEXTSTRING var text = ReadCharacters(); exp = new MethodInvocation(new MemberAccess(exp, "Print")).AddArguments(text); } return exp; default: throw new NotImplementedException(string.Format("DecodeParseString #{0:X2} is not implemented", _opCode & 0xF)); } } return exp; }
void IDisposable.Dispose() { Action method = ((IDisposable)this).Dispose; var invocation = new MethodInvocation(this, method.Method); var returns = pipeline.Invoke( invocation, (input, next) => { try { if (disposable != null) { disposable.Dispose(); } return(input.CreateValueReturn(null)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var token = root.FindToken(diagnostic.Location.SourceSpan.Start); var invocationExpression = token.Parent.FindContainer <InvocationExpressionSyntax>(); if (invocationExpression != null) { if (invocationExpression.ArgumentList.Arguments.Count == 0) { var invocation = new MethodInvocation(invocationExpression); context.RegisterCodeFix(CodeAction.Create(title: title, createChangedDocument: c => UseLocalVariablesAsParameters(context.Document, invocation, false, c), equivalenceKey: title), diagnostic); context.RegisterCodeFix(CodeAction.Create(title: titleWithNamed, createChangedDocument: c => UseLocalVariablesAsParameters(context.Document, invocation, true, c), equivalenceKey: titleWithNamed), diagnostic); } return; } var creationExpression = token.Parent.FindContainer <ObjectCreationExpressionSyntax>(); if (creationExpression != null && creationExpression.ArgumentList?.Arguments.Count == 0) { var invocation = new ConstructorInvocation(creationExpression); context.RegisterCodeFix(CodeAction.Create(title: title, createChangedDocument: c => UseLocalVariablesAsParameters(context.Document, invocation, false, c), equivalenceKey: title + "for constructor"), diagnostic); context.RegisterCodeFix(CodeAction.Create(title: titleWithNamed, createChangedDocument: c => UseLocalVariablesAsParameters(context.Document, invocation, true, c), equivalenceKey: titleWithNamed + "for constructor"), diagnostic); } }
public override void TurnOn() { Action method = base.TurnOn; var invocation = new MethodInvocation(this, method.Method); var returns = pipeline.Invoke( invocation, (input, next) => { try { if (target != null) { target.TurnOn(); } else { base.TurnOn(); } return(input.CreateValueReturn(null)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } }
public void invoke_with_out_parameters_happy_path() { var age = 0; double percentAwake = 0; var target = new Target(); var method = ReflectionHelper.GetMethod <Target>(x => x.GoOutput(null, out age, out percentAwake)); var values = new StepValues(method.Name); values.Store("name", "Grace Potter"); values.Store("age", 5); values.Store("percentAwake", .5); var invocation = MethodInvocation.For(method, target); invocation.Compile(target, CellHandling.Basic()); var results = invocation.Invoke(values).ToArray(); results.ShouldHaveTheSameElementsAs( new CellResult("age", ResultStatus.success), new CellResult("percentAwake", ResultStatus.success) ); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public Object invoke(org.aopalliance.intercept.MethodInvocation methodInvocation) throws Throwable public object invoke(MethodInvocation methodInvocation) { object result = methodInvocation.proceed(); outerInstance.persistVariable(name, scopedObject); return(result); }
public object HandleCall(MethodInvocation call) { return call.Proceed(); //ICacheHolder cacheHolder = call.Target as ICacheHolder; //if (cacheHolder != null) //{ // Hashtable cache = cacheHolder.Cache; // string key = string.Format("PerfromSomeReallyHeavyCalculationWoAop ({0})", 1.1); // //string key = call.ValueSignature; // if (!cache.ContainsKey(key)) // { // cache[key] = call.Proceed(); // // Console.WriteLine("adding result to cache"); // } // else // { // // Console.WriteLine("result fetched from cache"); // } // return cache[key]; //} //else //{ // return call.Proceed(); //} }
public void ExecutesNextIfNoBehaviors() { var invocation = new MethodInvocation(new FakeMock(), typeof(object).GetMethod(nameof(object.ToString))); var pipeline = new MockBehaviorPipeline(new MockSetup(invocation, Array.Empty <IArgumentMatcher>())); Assert.NotNull(pipeline.Execute(invocation, () => (m, n) => m.CreateValueReturn(null))); }
public override int this[int x, int y] { get { var method = ((MethodInfo)MethodBase.GetCurrentMethod()).GetBaseDefinition(); var invocation = new MethodInvocation(this, method, x, y); var returns = pipeline.Invoke( invocation, (input, next) => { try { var returnValue = target != null ? target[x, y] : base[x, y]; return(input.CreateValueReturn(returnValue, x, y)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } return(((int?)returns.ReturnValue).GetValueOrDefault()); } set { var method = ((MethodInfo)MethodBase.GetCurrentMethod()).GetBaseDefinition(); var invocation = new MethodInvocation(this, method); var returns = pipeline.Invoke( invocation, (input, next) => { try { if (target != null) { target[x, y] = value; } else { base[x, y] = value; } return(input.CreateValueReturn(null)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } } }
public WriteAction Visit(MethodInvocation methodInvocation) { return(Format("@.@(@)", Translate(methodInvocation.Instance), Translate(methodInvocation.MethodName), Translate(methodInvocation.Arguments, ", "))); }
public override int Add(int x, int y) { Func <int, int, int> method = base.Add; var invocation = new MethodInvocation(this, method.Method, x, y); var returns = pipeline.Invoke( invocation, (input, next) => { try { var returnValue = target != null ? target.Add(x, y) : base.Add(x, y); return(input.CreateValueReturn(returnValue, x, y)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } } ); var exception = returns.Exception; if (exception != null) { throw exception; } return(((int?)returns.ReturnValue).GetValueOrDefault()); }
public async Task StopConcurrentMethodRunnerQueueWhenMethodRunning() { var boundObject = new AsyncBoundObject(); var objectRepository = new JavascriptObjectRepository(); objectRepository.NameConverter = null; #if NETCOREAPP objectRepository.Register("testObject", boundObject, BindingOptions.DefaultBinder); #else objectRepository.Register("testObject", boundObject, true, BindingOptions.DefaultBinder); #endif var methodInvocation = new MethodInvocation(1, 1, 1, nameof(boundObject.AsyncWaitTwoSeconds), 1); methodInvocation.Parameters.Add("Echo Me!"); var methodRunnerQueue = new ConcurrentMethodRunnerQueue(objectRepository); methodRunnerQueue.Enqueue(methodInvocation); //Wait a litle for the queue to start processing our Method call await Task.Delay(500); var ex = Record.Exception(() => methodRunnerQueue.Dispose()); Assert.Null(ex); }
Statement SaveLoadGame() { var index = ((IntegerLiteralExpression)GetResultIndexExpression()).Value; var arg = GetVarOrDirectByte(OpCodeParameter.Param1); var result = new MethodInvocation("SaveLoadGame").AddArgument(arg); return SetResult(index, result).ToStatement(); }
// Build a method invocation with generic type names public static void BuildGenericMethodInvocation(IronyParser parser, Root root, Expression parentExpression, ParseTreeNode currentNode) { var methodInvocation = new MethodInvocation(parentExpression, currentNode.FindToken().Convert()); methodInvocation.Name = currentNode.ChildNodes[0].FindTokenAndGetText(); parentExpression.ChildExpressions.Add(methodInvocation); methodInvocation.ParentExpression = parentExpression; // Interpret the generic type names if (currentNode.ChildNodes[2].ChildNodes.Count > 0) { foreach (var n in currentNode.ChildNodes[2].ChildNodes) { methodInvocation.GenericTypes.Add(n.FindTokenAndGetText()); } } // interpret the expressions that are passed to the invocation as arguments if (currentNode.ChildNodes[4].ChildNodes.Count > 0) { foreach (var n in currentNode.ChildNodes[1].ChildNodes) { parser.ConsumeParseTree(root, methodInvocation.Parameters, n); } } }
public void Intercept(IInvocation invocation) { if (invocation.Method.DeclaringType == typeof(IProxy)) { invocation.ReturnValue = Behaviors; return; } var input = new MethodInvocation(invocation.InvocationTarget, invocation.Method, invocation.Arguments); var returns = pipeline.Invoke(input, (i, next) => { try { invocation.Proceed(); var returnValue = invocation.ReturnValue; return(input.CreateValueReturn(returnValue, invocation.Arguments)); } catch (Exception ex) { return(input.CreateExceptionReturn(ex)); } }); var exception = returns.Exception; if (exception != null) { throw exception; } invocation.ReturnValue = returns.ReturnValue; for (int i = 0; i < returns.Outputs.Count; i++) { var name = returns.Outputs.GetName(i); var index = input.Arguments.IndexOf(name); invocation.SetArgumentValue(index, returns.Outputs[index]); } }
public void correct_behavior_regarding_contravariance() { var sub = new MethodInvocation<Clong>(f => {}); var r = GetResolver(); r.Add(sub); r.GetSubscriptionsFor(new Clong()).ShouldHaveCount(1); r.GetSubscriptionsFor(new Clung()).ShouldHaveCount(1); }
public void Store(MethodInvocation methodInvocation) { var storage = GetStorageCollection(); if (storage != null) { storage.Push(methodInvocation); } }
public void correct_behavior_not_getting_message_twice() { var sub = new MethodInvocation<Clong>(f => { }); var r = GetResolver(); r.Add(sub); r.GetSubscriptionsFor(new Clong()).ShouldHaveCount(1); r.GetSubscriptionsFor(new Clong()).ShouldHaveCount(1); }
public object HandleCall(MethodInvocation call) { string key = call.ValueSignature; if (!cache.ContainsKey(key)) cache[key] = call.Proceed(); return cache[key]; }
public object HandleCall(MethodInvocation call) { // AsyncCallWrapper oneWay = new AsyncCallWrapper(call) ; oneWay.CallAsync() ; //since the method hasnt finished yet , we have to pass some return value return null; }
public object HandleCall(MethodInvocation call) { object res = call.Proceed(); InterceptedParameter param = (InterceptedParameter) call.Parameters[0]; param.Value = "some changed value"; return res; }
protected virtual Expression DecodeParseString(Expression target, bool withActor) { var b = ReadByte(); switch (b) { case 65: // SO_AT { var y = Pop(); var x = Pop(); target = new MethodInvocation(new MemberAccess(target, "At")).AddArguments(x, y); } break; case 66: // SO_COLOR { var color = Pop(); target = new MethodInvocation(new MemberAccess(target, "Color")).AddArguments(color); } break; case 67: // SO_CLIPPED { var right = Pop(); target = new MethodInvocation(new MemberAccess(target, "Clipped")).AddArguments(right); } break; case 69: // SO_CENTER target = new MethodInvocation(new MemberAccess(target, "Center")); break; case 71: // SO_LEFT target = new MethodInvocation(new MemberAccess(target, "Left")); break; case 72: // SO_OVERHEAD target = new MethodInvocation(new MemberAccess(target, "OverHead")); break; case 74: // SO_MUMBLE target = new MethodInvocation(new MemberAccess(target, "Mumble")); break; case 75: // SO_TEXTSTRING target = new MethodInvocation(new MemberAccess(target, "Text")).AddArgument(ReadCharacters()); break; case 0xFE: target = new MethodInvocation(new MemberAccess(target, "LoadDefault")); if (withActor) { var actor = Pop(); target = new MethodInvocation(new MemberAccess(target, "Actor")).AddArgument(actor); } break; case 0xFF: target = new MethodInvocation(new MemberAccess(target, "SaveDefault")); break; default: throw new NotSupportedException(string.Format("DecodeParseString: default case 0x{0:X}", b)); } return target; }
private string GetFactoryId(MethodInvocation call, FactoryMethodAttribute attrib) { string factoryId = null; if (attrib.FactoryId != null) factoryId = attrib.FactoryId; else factoryId = call.Method.Name; return factoryId; }
Statement RoomEffect() { var exp = new MethodInvocation("RoomEffect"); _opCode = ReadByte(); if ((_opCode & 0x1F) == 3) { var a = GetVarOrDirectWord(OpCodeParameter.Param1); exp.AddArgument(a); } return exp.ToStatement(); }
private object HandleGetProperty(MethodInvocation call) { IProxy proxy = (IProxy) call.Target; string propertyName = call.Method.Name.Substring(4); object value = call.Proceed(); bool cancel = false; Puzzle.NPersist.Framework.Interfaces.IInterceptor interceptor = proxy.GetInterceptor() ; if (interceptor != null) {interceptor.NotifyPropertyGet(call.Target,propertyName,ref value,ref cancel) ;} if (cancel) {return GetDefaultValue(call.ReturnType);} return value; }
public object HandleCall(MethodInvocation call) { // Console.WriteLine(call.ValueSignature) ; IInterceptableListState list = (IInterceptableListState)call.Target; list.Interceptor.BeforeCall() ; object res = call.Proceed() ; list.Interceptor.AfterCall() ; return res; }
protected virtual Statement CursorCommand() { var exp = new MethodInvocation("CursorCommand"); var subOp = ReadByte(); switch (subOp) { case 0x90: // SO_CURSOR_ON Turn cursor on exp = new MethodInvocation(new MemberAccess(exp, "SetCursor")).AddArgument(true); break; case 0x91: // SO_CURSOR_OFF Turn cursor off exp = new MethodInvocation(new MemberAccess(exp, "SetCursor")).AddArgument(false); break; case 0x92: // SO_USERPUT_ON exp = new MethodInvocation(new MemberAccess(exp, "SetUserInput")).AddArgument(true); break; case 0x93: // SO_USERPUT_OFF exp = new MethodInvocation(new MemberAccess(exp, "SetUserInput")).AddArgument(false); break; case 0x94: // SO_CURSOR_SOFT_ON Turn soft cursor on exp = new MethodInvocation(new MemberAccess(exp, "SetCursorSoft")).AddArgument(true); break; case 0x95: // SO_CURSOR_SOFT_OFF Turn soft cursor off exp = new MethodInvocation(new MemberAccess(exp, "SetCursorSoft")).AddArgument(false); break; case 0x96: // SO_USERPUT_SOFT_ON exp = new MethodInvocation(new MemberAccess(exp, "SetUserInputSoft")).AddArgument(true); break; case 0x97: // SO_USERPUT_SOFT_OFF exp = new MethodInvocation(new MemberAccess(exp, "SetUserInputSoft")).AddArgument(false); break; case 0x99: // SO_CURSOR_IMAGE Set cursor image exp = new MethodInvocation(new MemberAccess(exp, "SetCursorImage")).AddArguments(Pop(), Pop()); break; case 0x9A: // SO_CURSOR_HOTSPOT Set cursor hotspot exp = new MethodInvocation(new MemberAccess(exp, "SetCursorHotspot")).AddArguments(Pop(), Pop()); break; case 0x9C: // SO_CHARSET_SET exp = new MethodInvocation(new MemberAccess(exp, "InitCharset")).AddArgument(Pop()); break; case 0x9D: // SO_CHARSET_COLOR exp = new MethodInvocation(new MemberAccess(exp, "SetCharsetColor")).AddArgument(GetStackList(16)); break; case 0xD6: // SO_CURSOR_TRANSPARENT Set cursor transparent color exp = new MethodInvocation(new MemberAccess(exp, "SetCursorTransparentColor")).AddArgument(Pop()); break; default: throw new NotSupportedException(string.Format("CursorCommand: default case {0:X2}", subOp)); } return exp.ToStatement(); }
public object HandleCall(MethodInvocation call) { IProxy proxy = (IProxy)call.Target; string propertyName = call.Method.Name.Substring(4); IPropertyChangedHelper propertyChangedObj = (IPropertyChangedHelper)proxy; propertyChangedObj.OnPropertyChanging(propertyName); object res = call.Proceed(); propertyChangedObj.OnPropertyChanged(propertyName); return res; }
public object HandleCall(MethodInvocation call) { Type returnType = call.ReturnType; object res = null; try { res = call.Proceed(); } catch (Exception x) { throw new Exception("added exception", x); } return res; }
public object HandleCall(MethodInvocation call) { Type returnType = call.ReturnType; object res = null; try { res = call.Proceed(); } catch { if (returnType != null) res = GetDefaultValue(returnType); } return res; }
public object HandleCall(MethodInvocation call) { IProxy proxy = (IProxy)call.Target; string propertyName = call.Method.Name.Substring(4); object value = null; bool cancel = false; Puzzle.NPersist.Framework.Interfaces.IInterceptor interceptor = proxy.GetInterceptor(); if (interceptor != null) { interceptor.NotifyPropertyGet(call.Target, propertyName, ref value, ref cancel); } if (cancel) { return value; } value = call.Proceed(); if (interceptor != null) { interceptor.NotifyReadProperty(proxy, propertyName, ref value); } return value; }
public object HandleFastCall(IAopProxy target, object executionTarget, int methodIndex, IList parameters, Type returnType) { CallInfo info = MethodCache.GetCallInfo(methodIndex); MethodBase method = info.Method; IList interceptors = info.Interceptors; #if NET2 MethodInvocation invocation = new MethodInvocation(target, executionTarget, method, method , parameters, returnType, interceptors); invocation.Handler = info.Handler; #else MethodInfo wrapperMethod = (MethodInfo) MethodCache.wrapperMethodLookup[info.MethodId]; MethodInvocation invocation = new MethodInvocation(target, executionTarget, method, wrapperMethod , parameters, returnType, interceptors); #endif return invocation.Proceed(); }