How to use NewInstanceExpression class of Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST package

Best JustMockLite code snippet using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST.NewInstanceExpression

Run JustMockLite automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

NewInstanceExpression.cs

Source: NewInstanceExpression.cs Github

copy
1// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
2// 
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// 
7//   http://www.apache.org/licenses/LICENSE-2.0
8// 
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST
16{
17	using System;
18	using System.Reflection;
19	using System.Reflection.Emit;
20
21	internal class NewInstanceExpression : Expression
22	{
23		private readonly Expression[] arguments;
24		private readonly Type[] constructorArgs;
25		private readonly Type type;
26		private ConstructorInfo constructor;
27
28		public NewInstanceExpression(ConstructorInfo constructor, params Expression[] args)
29		{
30			this.constructor = constructor;
31			arguments = args;
32		}
33
34		public NewInstanceExpression(Type target, Type[] constructor_args, params Expression[] args)
35		{
36			type = target;
37			constructorArgs = constructor_args;
38			arguments = args;
39		}
40
41		public override void Emit(IMemberEmitter member, ILGenerator gen)
42		{
43			foreach (var exp in arguments)
44			{
45				exp.Emit(member, gen);
46			}
47
48			if (constructor == null)
49			{
50				constructor = type.GetConstructor(constructorArgs);
51			}
52
53			if (constructor == null)
54			{
55				throw new ProxyGenerationException("Could not find constructor matching specified arguments");
56			}
57
58			gen.Emit(OpCodes.Newobj, constructor);
59		}
60	}
61}
Full Screen

ThrowStatement.cs

Source: ThrowStatement.cs Github

copy
1// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
2// 
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// 
7//   http://www.apache.org/licenses/LICENSE-2.0
8// 
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST
16{
17	using System;
18	using System.Reflection.Emit;
19
20	internal class ThrowStatement : Statement
21	{
22		private readonly string errorMessage;
23		private readonly Type exceptionType;
24
25		public ThrowStatement(Type exceptionType, String errorMessage)
26		{
27			this.exceptionType = exceptionType;
28			this.errorMessage = errorMessage;
29		}
30
31		public override void Emit(IMemberEmitter member, ILGenerator gen)
32		{
33			var ci = exceptionType.GetConstructor(new[] { typeof(String) });
34			var constRef = new ConstReference(errorMessage);
35
36			var creationStmt = new NewInstanceExpression(ci, constRef.ToExpression());
37
38			creationStmt.Emit(member, gen);
39
40			gen.Emit(OpCodes.Throw);
41		}
42	}
43}
Full Screen

MethodWithInvocationGenerator.cs

Source: MethodWithInvocationGenerator.cs Github

copy
1// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
2// 
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// 
7//   http://www.apache.org/licenses/LICENSE-2.0
8// 
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15namespace Telerik.JustMock.Core.Castle.DynamicProxy.Generators
16{
17	using System;
18	using System.Diagnostics;
19	using System.Reflection;
20	using System.Reflection.Emit;
21#if FEATURE_SERIALIZATION
22	using System.Xml.Serialization;
23#endif
24
25	using Telerik.JustMock.Core.Castle.Core.Internal;
26	using Telerik.JustMock.Core.Castle.DynamicProxy.Contributors;
27	using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;
28	using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
29	using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
30	using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens;
31
32	internal class MethodWithInvocationGenerator : MethodGenerator
33	{
34		private readonly IInvocationCreationContributor contributor;
35		private readonly GetTargetExpressionDelegate getTargetExpression;
36		private readonly GetTargetExpressionDelegate getTargetTypeExpression;
37		private readonly Reference interceptors;
38		private readonly Type invocation;
39
40		public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation,
41		                                     GetTargetExpressionDelegate getTargetExpression,
42		                                     OverrideMethodDelegate createMethod, IInvocationCreationContributor contributor)
43			: this(method, interceptors, invocation, getTargetExpression, null, createMethod, contributor)
44		{
45		}
46
47		public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation,
48		                                     GetTargetExpressionDelegate getTargetExpression,
49		                                     GetTargetExpressionDelegate getTargetTypeExpression,
50		                                     OverrideMethodDelegate createMethod, IInvocationCreationContributor contributor)
51			: base(method, createMethod)
52		{
53			this.invocation = invocation;
54			this.getTargetExpression = getTargetExpression;
55			this.getTargetTypeExpression = getTargetTypeExpression;
56			this.interceptors = interceptors;
57			this.contributor = contributor;
58		}
59
60		protected FieldReference BuildMethodInterceptorsField(ClassEmitter @class, MethodInfo method, INamingScope namingScope)
61		{
62			var methodInterceptors = @class.CreateField(
63				namingScope.GetUniqueName(string.Format("interceptors_{0}", method.Name)),
64				typeof(IInterceptor[]),
65				false);
66#if FEATURE_SERIALIZATION
67			@class.DefineCustomAttributeFor<XmlIgnoreAttribute>(methodInterceptors);
68#endif
69			return methodInterceptors;
70		}
71
72		protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, ProxyGenerationOptions options, INamingScope namingScope)
73		{
74			var invocationType = invocation;
75
76			Trace.Assert(MethodToOverride.IsGenericMethod == invocationType.GetTypeInfo().IsGenericTypeDefinition);
77			var genericArguments = Type.EmptyTypes;
78
79			var constructor = invocation.GetConstructors()[0];
80
81			Expression proxiedMethodTokenExpression;
82			if (MethodToOverride.IsGenericMethod)
83			{
84				// bind generic method arguments to invocation's type arguments
85				genericArguments = emitter.MethodBuilder.GetGenericArguments();
86				invocationType = invocationType.MakeGenericType(genericArguments);
87				constructor = TypeBuilder.GetConstructor(invocationType, constructor);
88
89				// Not in the cache: generic method
90				proxiedMethodTokenExpression = new MethodTokenExpression(MethodToOverride.MakeGenericMethod(genericArguments));
91			}
92			else
93			{
94				var proxiedMethodToken = @class.CreateStaticField(namingScope.GetUniqueName("token_" + MethodToOverride.Name), typeof(MethodInfo));
95				@class.ClassConstructor.CodeBuilder.AddStatement(new AssignStatement(proxiedMethodToken, new MethodTokenExpression(MethodToOverride)));
96
97				proxiedMethodTokenExpression = proxiedMethodToken.ToExpression();
98			}
99
100			var methodInterceptors = SetMethodInterceptors(@class, namingScope, emitter, proxiedMethodTokenExpression);
101
102			var dereferencedArguments = IndirectReference.WrapIfByRef(emitter.Arguments);
103			var hasByRefArguments = HasByRefArguments(emitter.Arguments);
104
105			var arguments = GetCtorArguments(@class, proxiedMethodTokenExpression, dereferencedArguments, methodInterceptors);
106			var ctorArguments = ModifyArguments(@class, arguments);
107
108			var invocationLocal = emitter.CodeBuilder.DeclareLocal(invocationType);
109			emitter.CodeBuilder.AddStatement(new AssignStatement(invocationLocal,
110			                                                     new NewInstanceExpression(constructor, ctorArguments)));
111
112			if (MethodToOverride.ContainsGenericParameters)
113			{
114				EmitLoadGenricMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal);
115			}
116
117			if (hasByRefArguments)
118			{
119				emitter.CodeBuilder.AddStatement(new TryStatement());
120			}
121
122			var proceed = new ExpressionStatement(new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed));
123			emitter.CodeBuilder.AddStatement(proceed);
124
125			if (hasByRefArguments)
126			{
127				emitter.CodeBuilder.AddStatement(new FinallyStatement());
128			}
129
130			GeneratorUtil.CopyOutAndRefParameters(dereferencedArguments, invocationLocal, MethodToOverride, emitter);
131
132			if (hasByRefArguments)
133			{
134				emitter.CodeBuilder.AddStatement(new EndExceptionBlockStatement());
135			}
136
137			if (MethodToOverride.ReturnType != typeof(void))
138			{
139				var getRetVal = new MethodInvocationExpression(invocationLocal, InvocationMethods.GetReturnValue);
140
141				// Emit code to ensure a value type return type is not null, otherwise the cast will cause a null-deref
142				if (emitter.ReturnType.GetTypeInfo().IsValueType && !emitter.ReturnType.IsNullableType())
143				{
144					LocalReference returnValue = emitter.CodeBuilder.DeclareLocal(typeof(object));
145					emitter.CodeBuilder.AddStatement(new AssignStatement(returnValue, getRetVal));
146
147					emitter.CodeBuilder.AddExpression(new IfNullExpression(returnValue, new ThrowStatement(typeof(InvalidOperationException),
148						"Interceptors failed to set a return value, or swallowed the exception thrown by the target")));
149				}
150
151				// Emit code to return with cast from ReturnValue
152				emitter.CodeBuilder.AddStatement(new ReturnStatement(new ConvertExpression(emitter.ReturnType, getRetVal)));
153			}
154			else
155			{
156				emitter.CodeBuilder.AddStatement(new ReturnStatement());
157			}
158
159			return emitter;
160		}
161
162		private Expression SetMethodInterceptors(ClassEmitter @class, INamingScope namingScope, MethodEmitter emitter, Expression proxiedMethodTokenExpression)
163		{
164			var selector = @class.GetField("__selector");
165			if(selector == null)
166			{
167				return null;
168			}
169
170			var methodInterceptorsField = BuildMethodInterceptorsField(@class, MethodToOverride, namingScope);
171
172			Expression targetTypeExpression;
173			if (getTargetTypeExpression != null)
174			{
175				targetTypeExpression = getTargetTypeExpression(@class, MethodToOverride);
176			}
177			else
178			{
179				targetTypeExpression = new MethodInvocationExpression(null, TypeUtilMethods.GetTypeOrNull, getTargetExpression(@class, MethodToOverride));
180			}
181
182			var emptyInterceptors = new NewArrayExpression(0, typeof(IInterceptor));
183			var selectInterceptors = new MethodInvocationExpression(selector, InterceptorSelectorMethods.SelectInterceptors,
184			                                                        targetTypeExpression,
185			                                                        proxiedMethodTokenExpression, interceptors.ToExpression())
186			{ VirtualCall = true };
187
188			emitter.CodeBuilder.AddExpression(
189				new IfNullExpression(methodInterceptorsField,
190				                     new AssignStatement(methodInterceptorsField,
191				                                         new NullCoalescingOperatorExpression(selectInterceptors, emptyInterceptors))));
192
193			return methodInterceptorsField.ToExpression();
194		}
195
196		private void EmitLoadGenricMethodArguments(MethodEmitter methodEmitter, MethodInfo method, Reference invocationLocal)
197		{
198			var genericParameters = method.GetGenericArguments().FindAll(t => t.GetTypeInfo().IsGenericParameter);
199			var genericParamsArrayLocal = methodEmitter.CodeBuilder.DeclareLocal(typeof(Type[]));
200			methodEmitter.CodeBuilder.AddStatement(
201				new AssignStatement(genericParamsArrayLocal, new NewArrayExpression(genericParameters.Length, typeof(Type))));
202
203			for (var i = 0; i < genericParameters.Length; ++i)
204			{
205				methodEmitter.CodeBuilder.AddStatement(
206					new AssignArrayStatement(genericParamsArrayLocal, i, new TypeTokenExpression(genericParameters[i])));
207			}
208			methodEmitter.CodeBuilder.AddExpression(
209				new MethodInvocationExpression(invocationLocal,
210				                               InvocationMethods.SetGenericMethodArguments,
211				                               new ReferenceExpression(
212					                               genericParamsArrayLocal)));
213		}
214
215		private Expression[] GetCtorArguments(ClassEmitter @class, Expression proxiedMethodTokenExpression, TypeReference[] dereferencedArguments, Expression methodInterceptors)
216		{
217			return new[]
218			{
219				getTargetExpression(@class, MethodToOverride),
220				SelfReference.Self.ToExpression(),
221				methodInterceptors ?? interceptors.ToExpression(),
222				proxiedMethodTokenExpression,
223				new ReferencesToObjectArrayExpression(dereferencedArguments)
224			};
225		}
226
227		private Expression[] ModifyArguments(ClassEmitter @class, Expression[] arguments)
228		{
229			if (contributor == null)
230			{
231				return arguments;
232			}
233
234			return contributor.GetConstructorInvocationArguments(arguments, @class);
235		}
236
237		private bool HasByRefArguments(ArgumentReference[] arguments)
238		{
239			for (int i = 0; i < arguments.Length; i++ )
240			{
241				if (arguments[i].Type.GetTypeInfo().IsByRef)
242				{
243					return true;
244				}
245			}
246
247			return false;
248		}
249	}
250}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in NewInstanceExpression

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)