How to use CustomAttributeInfo class of Telerik.JustMock.Core.Castle.DynamicProxy package

Best JustMockLite code snippet using Telerik.JustMock.Core.Castle.DynamicProxy.CustomAttributeInfo

Run JustMockLite automation tests on LambdaTest cloud grid

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

AttributeUtil.cs

Source: AttributeUtil.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.Internal
16{
17	using System;
18	using System.Collections.Generic;
19	using System.Diagnostics;
20	using System.Linq;
21	using System.Reflection;
22    using System.Reflection.Emit;
23    using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
24
25	internal static class AttributeUtil
26	{
27		public static CustomAttributeInfo CreateInfo(CustomAttributeData attribute)
28		{
29			Debug.Assert(attribute != null, "attribute != null");
30
31			// .NET Core does not provide CustomAttributeData.Constructor, so we'll implement it
32			// by finding a constructor ourselves
33			Type[] constructorArgTypes;
34			object[] constructorArgs;
35			GetArguments(attribute.ConstructorArguments, out constructorArgTypes, out constructorArgs);
36#if FEATURE_LEGACY_REFLECTION_API
37			var constructor = attribute.Constructor;
38#else
39			var constructor = attribute.AttributeType.GetConstructor(constructorArgTypes);
40#endif
41
42			PropertyInfo[] properties;
43			object[] propertyValues;
44			FieldInfo[] fields;
45			object[] fieldValues;
46			GetSettersAndFields(
47#if FEATURE_LEGACY_REFLECTION_API
48				null,
49#else
50				attribute.AttributeType,
51#endif
52				attribute.NamedArguments, out properties, out propertyValues, out fields, out fieldValues);
53
54			return new CustomAttributeInfo(constructor,
55			                               constructorArgs,
56			                               properties,
57			                               propertyValues,
58			                               fields,
59			                               fieldValues);
60		}
61
62		private static void GetArguments(IList<CustomAttributeTypedArgument> constructorArguments,
63			out Type[] constructorArgTypes, out object[] constructorArgs)
64		{
65			constructorArgTypes = new Type[constructorArguments.Count];
66			constructorArgs = new object[constructorArguments.Count];
67			for (var i = 0; i < constructorArguments.Count; i++)
68			{
69				constructorArgTypes[i] = constructorArguments[i].ArgumentType;
70				constructorArgs[i] = ReadAttributeValue(constructorArguments[i]);
71			}
72		}
73
74		private static object[] GetArguments(IList<CustomAttributeTypedArgument> constructorArguments)
75		{
76			var arguments = new object[constructorArguments.Count];
77			for (var i = 0; i < constructorArguments.Count; i++)
78			{
79				arguments[i] = ReadAttributeValue(constructorArguments[i]);
80			}
81
82			return arguments;
83		}
84
85		private static object ReadAttributeValue(CustomAttributeTypedArgument argument)
86		{
87			var value = argument.Value;
88			if (argument.ArgumentType.GetTypeInfo().IsArray == false)
89			{
90				return value;
91			}
92			//special case for handling arrays in attributes
93			var arguments = GetArguments((IList<CustomAttributeTypedArgument>)value);
94			var array = new object[arguments.Length];
95			arguments.CopyTo(array, 0);
96			return array;
97		}
98
99		private static void GetSettersAndFields(Type attributeType, IEnumerable<CustomAttributeNamedArgument> namedArguments,
100			out PropertyInfo[] properties, out object[] propertyValues,
101			out FieldInfo[] fields, out object[] fieldValues)
102		{
103			var propertyList = new List<PropertyInfo>();
104			var propertyValuesList = new List<object>();
105			var fieldList = new List<FieldInfo>();
106			var fieldValuesList = new List<object>();
107			foreach (var argument in namedArguments)
108			{
109#if FEATURE_LEGACY_REFLECTION_API
110				if (argument.MemberInfo.MemberType == MemberTypes.Field)
111				{
112					fieldList.Add(argument.MemberInfo as FieldInfo);
113					fieldValuesList.Add(ReadAttributeValue(argument.TypedValue));
114				}
115				else
116				{
117					propertyList.Add(argument.MemberInfo as PropertyInfo);
118					propertyValuesList.Add(ReadAttributeValue(argument.TypedValue));
119				}
120#else
121				if (argument.IsField)
122				{
123					fieldList.Add(attributeType.GetField(argument.MemberName));
124					fieldValuesList.Add(ReadAttributeValue(argument.TypedValue));
125				}
126				else
127				{
128					propertyList.Add(attributeType.GetProperty(argument.MemberName));
129					propertyValuesList.Add(ReadAttributeValue(argument.TypedValue));
130				}
131#endif
132			}
133
134			properties = propertyList.ToArray();
135			propertyValues = propertyValuesList.ToArray();
136			fields = fieldList.ToArray();
137			fieldValues = fieldValuesList.ToArray();
138		}
139
140		public static IEnumerable<CustomAttributeInfo> GetNonInheritableAttributes(this MemberInfo member)
141		{
142			Debug.Assert(member != null, "member != null");
143#if FEATURE_LEGACY_REFLECTION_API
144			var attributes = CustomAttributeData.GetCustomAttributes(member);
145#else
146			var attributes = member.CustomAttributes;
147#endif
148
149			foreach (var attribute in attributes)
150			{
151#if FEATURE_LEGACY_REFLECTION_API
152				var attributeType = attribute.Constructor.DeclaringType;
153#else
154				var attributeType = attribute.AttributeType;
155#endif
156				if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance: false))
157				{
158					continue;
159				}
160
161				CustomAttributeInfo info;
162				try
163				{
164					info = CreateInfo(attribute);
165				}
166				catch (ArgumentException e)
167				{
168					var message =
169						string.Format(
170							"Due to limitations in CLR, DynamicProxy was unable to successfully replicate non-inheritable attribute {0} on {1}{2}. " +
171							"To avoid this error you can chose not to replicate this attribute type by calling '{3}.Add(typeof({0}))'.",
172							attributeType.FullName,
173							member.DeclaringType.FullName,
174#if FEATURE_LEGACY_REFLECTION_API
175							(member is Type) ? "" : ("." + member.Name),
176#else
177							(member is TypeInfo) ? "" : ("." + member.Name),
178#endif
179							typeof(AttributesToAvoidReplicating).FullName);
180					throw new ProxyGenerationException(message, e);
181				}
182				if (info != null)
183				{
184					yield return info;
185				}
186			}
187		}
188
189		public static IEnumerable<CustomAttributeInfo> GetNonInheritableAttributes(this ParameterInfo parameter)
190		{
191			Debug.Assert(parameter != null, "parameter != null");
192
193#if FEATURE_LEGACY_REFLECTION_API
194			var attributes = CustomAttributeData.GetCustomAttributes(parameter);
195#else
196			var attributes = parameter.CustomAttributes;
197#endif
198
199			var ignoreInheritance = parameter.Member is ConstructorInfo;
200
201			foreach (var attribute in attributes)
202			{
203#if FEATURE_LEGACY_REFLECTION_API
204				var attributeType = attribute.Constructor.DeclaringType;
205#else
206				var attributeType = attribute.AttributeType;
207#endif
208
209				if (ShouldSkipAttributeReplication(attributeType, ignoreInheritance))
210				{
211					continue;
212				}
213
214				var info = CreateInfo(attribute);
215				if (info != null)
216				{
217					yield return info;
218				}
219			}
220		}
221
222		/// <summary>
223		///   Attributes should be replicated if they are non-inheritable,
224		///   but there are some special cases where the attributes means
225		///   something to the CLR, where they should be skipped.
226		/// </summary>
227		private static bool ShouldSkipAttributeReplication(Type attribute, bool ignoreInheritance)
228		{
229			if (attribute.GetTypeInfo().IsPublic == false)
230			{
231				return true;
232			}
233
234			if (AttributesToAvoidReplicating.ShouldAvoid(attribute))
235			{
236				return true;
237			}
238
239			// Later, there might be more special cases requiring attribute replication,
240			// which might justify creating a `SpecialCaseAttributeThatShouldBeReplicated`
241			// method and an `AttributesToAlwaysReplicate` class. For the moment, `Param-
242			// ArrayAttribute` is the only special case, so keep it simple for now:
243			if (attribute == typeof(ParamArrayAttribute))
244			{
245				return false;
246			}
247
248			if (!ignoreInheritance)
249			{
250				var attrs = attribute.GetTypeInfo().GetCustomAttributes<AttributeUsageAttribute>(true).ToArray();
251				if (attrs.Length != 0)
252				{
253					return attrs[0].Inherited;
254				}
255
256				return true;
257			}
258
259			return false;
260		}
261
262		public static CustomAttributeInfo CreateInfo<TAttribute>() where TAttribute : Attribute, new()
263		{
264			var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes);
265			Debug.Assert(constructor != null, "constructor != null");
266
267			return new CustomAttributeInfo(constructor, new object[0]);
268		}
269
270		public static CustomAttributeInfo CreateInfo(Type attribute, object[] constructorArguments)
271		{
272			Debug.Assert(attribute != null, "attribute != null");
273			Debug.Assert(typeof(Attribute).IsAssignableFrom(attribute), "typeof(Attribute).IsAssignableFrom(attribute)");
274			Debug.Assert(constructorArguments != null, "constructorArguments != null");
275
276			var constructor = attribute.GetConstructor(GetTypes(constructorArguments));
277			Debug.Assert(constructor != null, "constructor != null");
278
279			return new CustomAttributeInfo(constructor, constructorArguments);
280		}
281
282		private static Type[] GetTypes(object[] objects)
283		{
284			var types = new Type[objects.Length];
285			for (var i = 0; i < types.Length; i++)
286			{
287				types[i] = objects[i].GetType();
288			}
289			return types;
290		}
291
292        public static CustomAttributeBuilder CreateBuilder<TAttribute>() where TAttribute : Attribute, new()
293        {
294            var constructor = typeof(TAttribute).GetConstructor(Type.EmptyTypes);
295            Debug.Assert(constructor != null, "constructor != null");
296
297            return new CustomAttributeBuilder(constructor, new object[0]);
298        }
299    }
300}
Full Screen

AbstractTypeEmitter.cs

Source: AbstractTypeEmitter.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
16{
17	using System;
18	using System.Collections.Generic;
19	using System.Diagnostics;
20	using System.Reflection;
21	using System.Reflection.Emit;
22
23	using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
24	using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
25
26	internal abstract class AbstractTypeEmitter
27	{
28		private const MethodAttributes defaultAttributes =
29			MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public;
30
31		private readonly ConstructorCollection constructors;
32		private readonly EventCollection events;
33
34		private readonly IDictionary<string, FieldReference> fields =
35			new Dictionary<string, FieldReference>(StringComparer.OrdinalIgnoreCase);
36
37		private readonly MethodCollection methods;
38
39		private readonly Dictionary<String, GenericTypeParameterBuilder> name2GenericType;
40		private readonly NestedClassCollection nested;
41		private readonly PropertiesCollection properties;
42		private readonly TypeBuilder typebuilder;
43
44		private GenericTypeParameterBuilder[] genericTypeParams;
45
46		protected AbstractTypeEmitter(TypeBuilder typeBuilder)
47		{
48			typebuilder = typeBuilder;
49			nested = new NestedClassCollection();
50			methods = new MethodCollection();
51			constructors = new ConstructorCollection();
52			properties = new PropertiesCollection();
53			events = new EventCollection();
54			name2GenericType = new Dictionary<String, GenericTypeParameterBuilder>();
55		}
56
57		public Type BaseType
58		{
59			get
60			{
61				if (TypeBuilder.IsInterface)
62				{
63					throw new InvalidOperationException("This emitter represents an interface; interfaces have no base types.");
64				}
65				return TypeBuilder.BaseType;
66			}
67		}
68
69		public TypeConstructorEmitter ClassConstructor { get; private set; }
70
71		public ConstructorCollection Constructors
72		{
73			get { return constructors; }
74		}
75
76		public GenericTypeParameterBuilder[] GenericTypeParams
77		{
78			get { return genericTypeParams; }
79		}
80
81		public NestedClassCollection Nested
82		{
83			get { return nested; }
84		}
85
86		public TypeBuilder TypeBuilder
87		{
88			get { return typebuilder; }
89		}
90
91		public void AddCustomAttributes(ProxyGenerationOptions proxyGenerationOptions)
92		{
93            foreach (var attribute in proxyGenerationOptions.AdditionalAttributes)
94			{
95				typebuilder.SetCustomAttribute(attribute.Builder);
96			}
97		}
98
99		public virtual Type BuildType()
100		{
101			EnsureBuildersAreInAValidState();
102
103			var type = CreateType(typebuilder);
104
105			foreach (var builder in nested)
106			{
107				builder.BuildType();
108			}
109
110			return type;
111		}
112
113		public void CopyGenericParametersFromMethod(MethodInfo methodToCopyGenericsFrom)
114		{
115			// big sanity check
116			if (genericTypeParams != null)
117			{
118				throw new ProxyGenerationException("CopyGenericParametersFromMethod: cannot invoke me twice");
119			}
120
121			SetGenericTypeParameters(GenericUtil.CopyGenericArguments(methodToCopyGenericsFrom, typebuilder, name2GenericType));
122		}
123
124		public ConstructorEmitter CreateConstructor(params ArgumentReference[] arguments)
125		{
126			if (TypeBuilder.IsInterface)
127			{
128				throw new InvalidOperationException("Interfaces cannot have constructors.");
129			}
130
131			var member = new ConstructorEmitter(this, arguments);
132			constructors.Add(member);
133			return member;
134		}
135
136		public void CreateDefaultConstructor()
137		{
138			if (TypeBuilder.IsInterface)
139			{
140				throw new InvalidOperationException("Interfaces cannot have constructors.");
141			}
142
143			constructors.Add(new ConstructorEmitter(this));
144		}
145
146		public EventEmitter CreateEvent(string name, EventAttributes atts, Type type)
147		{
148			var eventEmitter = new EventEmitter(this, name, atts, type);
149			events.Add(eventEmitter);
150			return eventEmitter;
151		}
152
153		public FieldReference CreateField(string name, Type fieldType)
154		{
155			return CreateField(name, fieldType, true);
156		}
157
158		public FieldReference CreateField(string name, Type fieldType, bool serializable)
159		{
160			var atts = FieldAttributes.Private;
161
162			if (!serializable)
163			{
164				atts |= FieldAttributes.NotSerialized;
165			}
166
167			return CreateField(name, fieldType, atts);
168		}
169
170		public FieldReference CreateField(string name, Type fieldType, FieldAttributes atts)
171		{
172			var fieldBuilder = typebuilder.DefineField(name, fieldType, atts);
173			var reference = new FieldReference(fieldBuilder);
174			fields[name] = reference;
175			return reference;
176		}
177
178		public MethodEmitter CreateMethod(string name, MethodAttributes attrs, Type returnType, params Type[] argumentTypes)
179		{
180			var member = new MethodEmitter(this, name, attrs, returnType, argumentTypes ?? Type.EmptyTypes);
181			methods.Add(member);
182			return member;
183		}
184
185		public MethodEmitter CreateMethod(string name, Type returnType, params Type[] parameterTypes)
186		{
187			return CreateMethod(name, defaultAttributes, returnType, parameterTypes);
188		}
189
190		public MethodEmitter CreateMethod(string name, MethodInfo methodToUseAsATemplate)
191		{
192			return CreateMethod(name, defaultAttributes, methodToUseAsATemplate);
193		}
194
195		public MethodEmitter CreateMethod(string name, MethodAttributes attributes, MethodInfo methodToUseAsATemplate)
196		{
197			var method = new MethodEmitter(this, name, attributes, methodToUseAsATemplate);
198			methods.Add(method);
199			return method;
200		}
201
202		public PropertyEmitter CreateProperty(string name, PropertyAttributes attributes, Type propertyType, Type[] arguments)
203		{
204			var propEmitter = new PropertyEmitter(this, name, attributes, propertyType, arguments);
205			properties.Add(propEmitter);
206			return propEmitter;
207		}
208
209		public FieldReference CreateStaticField(string name, Type fieldType)
210		{
211			return CreateStaticField(name, fieldType, FieldAttributes.Private);
212		}
213
214		public FieldReference CreateStaticField(string name, Type fieldType, FieldAttributes atts)
215		{
216			atts |= FieldAttributes.Static;
217			return CreateField(name, fieldType, atts);
218		}
219
220		public ConstructorEmitter CreateTypeConstructor()
221		{
222			var member = new TypeConstructorEmitter(this);
223			constructors.Add(member);
224			ClassConstructor = member;
225			return member;
226		}
227
228		public void DefineCustomAttribute(CustomAttributeBuilder attribute)
229		{
230			typebuilder.SetCustomAttribute(attribute);
231		}
232
233		public void DefineCustomAttribute<TAttribute>(object[] constructorArguments) where TAttribute : Attribute
234		{
235			var customAttributeInfo = AttributeUtil.CreateInfo(typeof(TAttribute), constructorArguments);
236			typebuilder.SetCustomAttribute(customAttributeInfo.Builder);
237		}
238
239		public void DefineCustomAttribute<TAttribute>() where TAttribute : Attribute, new()
240		{
241			var customAttributeInfo = AttributeUtil.CreateInfo<TAttribute>();
242			typebuilder.SetCustomAttribute(customAttributeInfo.Builder);
243		}
244
245		public void DefineCustomAttributeFor<TAttribute>(FieldReference field) where TAttribute : Attribute, new()
246		{
247			var customAttributeInfo = AttributeUtil.CreateInfo<TAttribute>();
248			var fieldbuilder = field.Fieldbuilder;
249			if (fieldbuilder == null)
250			{
251				throw new ArgumentException(
252					"Invalid field reference.This reference does not point to field on type being generated", "field");
253			}
254			fieldbuilder.SetCustomAttribute(customAttributeInfo.Builder);
255		}
256
257		public IEnumerable<FieldReference> GetAllFields()
258		{
259			return fields.Values;
260		}
261
262		public FieldReference GetField(string name)
263		{
264			if (string.IsNullOrEmpty(name))
265			{
266				return null;
267			}
268
269			FieldReference value;
270			fields.TryGetValue(name, out value);
271			return value;
272		}
273
274		public Type GetGenericArgument(String genericArgumentName)
275		{
276			if (name2GenericType.ContainsKey(genericArgumentName))
277				return name2GenericType[genericArgumentName].AsType();
278
279			return null;
280		}
281
282		public Type[] GetGenericArgumentsFor(Type genericType)
283		{
284			var types = new List<Type>();
285
286			foreach (var genType in genericType.GetGenericArguments())
287			{
288				if (genType.GetTypeInfo().IsGenericParameter)
289				{
290					types.Add(name2GenericType[genType.Name].AsType());
291				}
292				else
293				{
294					types.Add(genType);
295				}
296			}
297
298			return types.ToArray();
299		}
300
301		public Type[] GetGenericArgumentsFor(MethodInfo genericMethod)
302		{
303			var types = new List<Type>();
304			foreach (var genType in genericMethod.GetGenericArguments())
305			{
306				types.Add(name2GenericType[genType.Name].AsType());
307			}
308
309			return types.ToArray();
310		}
311
312		public void SetGenericTypeParameters(GenericTypeParameterBuilder[] genericTypeParameterBuilders)
313		{
314			genericTypeParams = genericTypeParameterBuilders;
315		}
316
317		protected Type CreateType(TypeBuilder type)
318		{
319			try
320			{
321#if FEATURE_LEGACY_REFLECTION_API
322				return type.CreateType();
323#else
324				return type.CreateTypeInfo().AsType();
325#endif
326			}
327			catch (BadImageFormatException ex)
328			{
329				if (Debugger.IsAttached == false)
330				{
331					throw;
332				}
333
334				if (ex.Message.Contains(@"HRESULT: 0x8007000B") == false)
335				{
336					throw;
337				}
338
339				if (type.IsGenericTypeDefinition == false)
340				{
341					throw;
342				}
343
344				var message =
345					"This is a DynamicProxy2 error: It looks like you encountered a bug in Visual Studio debugger, " +
346					"which causes this exception when proxying types with generic methods having constraints on their generic arguments." +
347					"This code will work just fine without the debugger attached. " +
348					"If you wish to use debugger you may have to switch to Visual Studio 2010 where this bug was fixed.";
349				var exception = new ProxyGenerationException(message);
350				exception.Data.Add("ProxyType", type.ToString());
351				throw exception;
352			}
353		}
354
355		protected virtual void EnsureBuildersAreInAValidState()
356		{
357			if (!typebuilder.IsInterface && constructors.Count == 0)
358			{
359				CreateDefaultConstructor();
360			}
361
362			foreach (IMemberEmitter builder in properties)
363			{
364				builder.EnsureValidCodeBlock();
365				builder.Generate();
366			}
367			foreach (IMemberEmitter builder in events)
368			{
369				builder.EnsureValidCodeBlock();
370				builder.Generate();
371			}
372			foreach (IMemberEmitter builder in constructors)
373			{
374				builder.EnsureValidCodeBlock();
375				builder.Generate();
376			}
377			foreach (IMemberEmitter builder in methods)
378			{
379				builder.EnsureValidCodeBlock();
380				builder.Generate();
381			}
382		}
383	}
384}
Full Screen

ProxyGenerationOptions.cs

Source: ProxyGenerationOptions.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
16{
17	using System;
18	using System.Collections.Generic;
19	using System.Reflection.Emit;
20#if FEATURE_SERIALIZATION
21	using System.Runtime.Serialization;
22#endif
23    using CollectionExtensions = Telerik.JustMock.Core.Castle.Core.Internal.CollectionExtensions;
24#if DOTNET40
25	using System.Security;
26#endif
27
28#if FEATURE_SERIALIZATION
29	[Serializable]
30#endif
31    internal class ProxyGenerationOptions
32#if FEATURE_SERIALIZATION
33		: ISerializable
34#endif
35	{
36		public static readonly ProxyGenerationOptions Default = new ProxyGenerationOptions();
37
38		private List<object> mixins;
39		internal readonly IList<Attribute> attributesToAddToGeneratedTypes = new List<Attribute>();
40		private readonly IList<CustomAttributeInfo> additionalAttributes = new List<CustomAttributeInfo>();
41
42#if FEATURE_SERIALIZATION
43		[NonSerialized]
44#endif
45		private MixinData mixinData; // this is calculated dynamically on proxy type creation
46
47		/// <summary>
48		///   Initializes a new instance of the <see cref = "ProxyGenerationOptions" /> class.
49		/// </summary>
50		/// <param name = "hook">The hook.</param>
51		public ProxyGenerationOptions(IProxyGenerationHook hook)
52		{
53			BaseTypeForInterfaceProxy = typeof(object);
54			Hook = hook;
55		}
56
57		/// <summary>
58		///   Initializes a new instance of the <see cref = "ProxyGenerationOptions" /> class.
59		/// </summary>
60		public ProxyGenerationOptions()
61			: this(new AllMethodsHook())
62		{
63		}
64
65#if FEATURE_SERIALIZATION
66		private ProxyGenerationOptions(SerializationInfo info, StreamingContext context)
67		{
68			Hook = (IProxyGenerationHook)info.GetValue("hook", typeof(IProxyGenerationHook));
69			Selector = (IInterceptorSelector)info.GetValue("selector", typeof(IInterceptorSelector));
70			mixins = (List<object>)info.GetValue("mixins", typeof(List<object>));
71			BaseTypeForInterfaceProxy = Type.GetType(info.GetString("baseTypeForInterfaceProxy.AssemblyQualifiedName"));
72		}
73#endif
74
75		public void Initialize()
76		{
77			if (mixinData == null)
78			{
79				try
80				{
81					mixinData = new MixinData(mixins);
82				}
83				catch (ArgumentException ex)
84				{
85					throw new InvalidMixinConfigurationException(
86						"There is a problem with the mixins added to this ProxyGenerationOptions: " + ex.Message, ex);
87				}
88			}
89		}
90
91#if FEATURE_SERIALIZATION
92#if FEATURE_SECURITY_PERMISSIONS && DOTNET40
93		[SecurityCritical]
94#endif
95		public void GetObjectData(SerializationInfo info, StreamingContext context)
96		{
97			info.AddValue("hook", Hook);
98			info.AddValue("selector", Selector);
99			info.AddValue("mixins", mixins);
100			info.AddValue("baseTypeForInterfaceProxy.AssemblyQualifiedName", BaseTypeForInterfaceProxy.AssemblyQualifiedName);
101		}
102#endif
103
104		public IProxyGenerationHook Hook { get; set; }
105
106		public IInterceptorSelector Selector { get; set; }
107
108		public Type BaseTypeForInterfaceProxy { get; set; }
109
110		public IList<CustomAttributeInfo> AdditionalAttributes
111		{
112			get { return additionalAttributes; }
113		}
114
115		public MixinData MixinData
116		{
117			get
118			{
119				if (mixinData == null)
120				{
121					throw new InvalidOperationException("Call Initialize before accessing the MixinData property.");
122				}
123				return mixinData;
124			}
125		}
126
127		public void AddMixinInstance(object instance)
128		{
129			if (instance == null)
130			{
131				throw new ArgumentNullException("instance");
132			}
133
134			if (mixins == null)
135			{
136				mixins = new List<object>();
137			}
138
139			mixins.Add(instance);
140			mixinData = null;
141		}
142
143		public object[] MixinsAsArray()
144		{
145			if (mixins == null)
146			{
147				return new object[0];
148			}
149
150			return mixins.ToArray();
151		}
152
153		public bool HasMixins
154		{
155			get { return mixins != null && mixins.Count != 0; }
156		}
157
158		public override bool Equals(object obj)
159		{
160			if (ReferenceEquals(this, obj))
161			{
162				return true;
163			}
164
165			var proxyGenerationOptions = obj as ProxyGenerationOptions;
166			if (ReferenceEquals(proxyGenerationOptions, null))
167			{
168				return false;
169			}
170
171			// ensure initialization before accessing MixinData
172			Initialize();
173			proxyGenerationOptions.Initialize();
174
175			if (!Equals(Hook, proxyGenerationOptions.Hook))
176			{
177				return false;
178			}
179			if (!Equals(Selector == null, proxyGenerationOptions.Selector == null))
180			{
181				return false;
182			}
183			if (!Equals(MixinData, proxyGenerationOptions.MixinData))
184			{
185				return false;
186			}
187			if (!Equals(BaseTypeForInterfaceProxy, proxyGenerationOptions.BaseTypeForInterfaceProxy))
188			{
189				return false;
190			}
191			if (!CollectionExtensions.AreEquivalent(AdditionalAttributes, proxyGenerationOptions.AdditionalAttributes))
192			{
193				return false;
194			}
195			return true;
196		}
197
198		public override int GetHashCode()
199		{
200			// ensure initialization before accessing MixinData
201			Initialize();
202
203			var result = Hook != null ? Hook.GetType().GetHashCode() : 0;
204			result = 29*result + (Selector != null ? 1 : 0);
205			result = 29*result + MixinData.GetHashCode();
206			result = 29*result + (BaseTypeForInterfaceProxy != null ? BaseTypeForInterfaceProxy.GetHashCode() : 0);
207			result = 29*result + CollectionExtensions.GetContentsHashCode(AdditionalAttributes);
208			return result;
209		}
210	}
211}
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

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)