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

Best JustMockLite code snippet using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.AttributeDisassembler

AttributeDisassembler.cs

Source:AttributeDisassembler.cs Github

copy

Full Screen

...18	using System.Diagnostics;19	using System.Reflection;20	using System.Reflection.Emit;21	using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;22	internal class AttributeDisassembler : IAttributeDisassembler23	{24		public CustomAttributeBuilder Disassemble(Attribute attribute)25		{26			var type = attribute.GetType();27			try28			{29				ConstructorInfo ctor;30				var ctorArgs = GetConstructorAndArgs(type, attribute, out ctor);31				var replicated = (Attribute)Activator.CreateInstance(type, ctorArgs);32				PropertyInfo[] properties;33				var propertyValues = GetPropertyValues(type, out properties, attribute, replicated);34				FieldInfo[] fields;35				var fieldValues = GetFieldValues(type, out fields, attribute, replicated);36				return new CustomAttributeBuilder(ctor, ctorArgs, properties, propertyValues, fields, fieldValues);37			}38			catch (Exception ex)39			{40				// there is no real way to log a warning here...41				return HandleError(type, ex);42			}43		}44		/// <summary>45		///   Handles error during disassembly process46		/// </summary>47		/// <param name = "attributeType">Type of the attribute being disassembled</param>48		/// <param name = "exception">Exception thrown during the process</param>49		/// <returns>usually null, or (re)throws the exception</returns>50		protected virtual CustomAttributeBuilder HandleError(Type attributeType, Exception exception)51		{52			// ouch...53			var message = "DynamicProxy was unable to disassemble attribute " + attributeType.Name +54			              " using default AttributeDisassembler. " +55			              string.Format("To handle the disassembly process properly implement the {0} interface, ",56			                            typeof(IAttributeDisassembler)) +57			              "and register your disassembler to handle this type of attributes using " +58			              typeof(AttributeUtil).Name + ".AddDisassembler<" + attributeType.Name + ">(yourDisassembler) method";59			throw new ProxyGenerationException(message, exception);60		}61		private static object[] GetConstructorAndArgs(Type attributeType, Attribute attribute, out ConstructorInfo ctor)62		{63			ctor = attributeType.GetConstructors()[0];64			var constructorParams = ctor.GetParameters();65			if (constructorParams.Length == 0)66			{67				return new object[0];68			}69			return InitializeConstructorArgs(attributeType, attribute, constructorParams);70		}71		private static object[] GetPropertyValues(Type attType, out PropertyInfo[] properties, Attribute original,72		                                          Attribute replicated)73		{74			var propertyCandidates = GetPropertyCandidates(attType);75			var selectedValues = new List<object>(propertyCandidates.Count);76			var selectedProperties = new List<PropertyInfo>(propertyCandidates.Count);77			foreach (var property in propertyCandidates)78			{79				var originalValue = property.GetValue(original, null);80				var replicatedValue = property.GetValue(replicated, null);81				if (AreAttributeElementsEqual(originalValue, replicatedValue))82				{83					//this property has default value so we skip it84					continue;85				}86				selectedProperties.Add(property);87				selectedValues.Add(originalValue);88			}89			properties = selectedProperties.ToArray();90			return selectedValues.ToArray();91		}92		private static object[] GetFieldValues(Type attType, out FieldInfo[] fields, Attribute original, Attribute replicated)93		{94			var fieldsCandidates = attType.GetFields(BindingFlags.Public | BindingFlags.Instance);95			var selectedValues = new List<object>(fieldsCandidates.Length);96			var selectedFields = new List<FieldInfo>(fieldsCandidates.Length);97			foreach (var field in fieldsCandidates)98			{99				var originalValue = field.GetValue(original);100				var replicatedValue = field.GetValue(replicated);101				if (AreAttributeElementsEqual(originalValue, replicatedValue))102				{103					//this field has default value so we skip it104					continue;105				}106				selectedFields.Add(field);107				selectedValues.Add(originalValue);108			}109			fields = selectedFields.ToArray();110			return selectedValues.ToArray();111		}112		/// <summary>113		///   Here we try to match a constructor argument to its value.114		///   Since we can't get the values from the assembly, we use some heuristics to get it.115		///   a/ we first try to match all the properties on the attributes by name (case insensitive) to the argument116		///   b/ if we fail we try to match them by property type, with some smarts about convertions (i,e: can use Guid for string).117		/// </summary>118		private static object[] InitializeConstructorArgs(Type attributeType, Attribute attribute, ParameterInfo[] parameters)119		{120			var args = new object[parameters.Length];121			for (var i = 0; i < args.Length; i++)122			{123				args[i] = GetArgumentValue(attributeType, attribute, parameters[i]);124			}125			return args;126		}127		private static object GetArgumentValue(Type attributeType, Attribute attribute, ParameterInfo parameter)128		{129			var properties = attributeType.GetProperties();130			//first try to find a property with 131			foreach (var property in properties)132			{133				if (property.CanRead == false && property.GetIndexParameters().Length != 0)134				{135					continue;136				}137				if (String.Compare(property.Name, parameter.Name, StringComparison.CurrentCultureIgnoreCase) == 0)138				{139					return ConvertValue(property.GetValue(attribute, null), parameter.ParameterType);140				}141			}142			PropertyInfo bestMatch = null;143			//now we try to find it by type144			foreach (var property in properties)145			{146				if (property.CanRead == false && property.GetIndexParameters().Length != 0)147				{148					continue;149				}150				bestMatch = ReplaceIfBetterMatch(parameter, property, bestMatch);151			}152			if (bestMatch != null)153			{154				return ConvertValue(bestMatch.GetValue(attribute, null), parameter.ParameterType);155			}156			return GetDefaultValueFor(parameter);157		}158		/// <summary>159		///   We have the following rules here.160		///   Try to find a matching type, failing that, if the parameter is string, get the first property (under the assumption that161		///   we can convert it.162		/// </summary>163		private static PropertyInfo ReplaceIfBetterMatch(ParameterInfo parameterInfo, PropertyInfo propertyInfo,164		                                                 PropertyInfo bestMatch)165		{166			var notBestMatch = bestMatch == null || bestMatch.PropertyType != parameterInfo.ParameterType;167			if (propertyInfo.PropertyType == parameterInfo.ParameterType && notBestMatch)168			{169				return propertyInfo;170			}171			if (parameterInfo.ParameterType == typeof(string) && notBestMatch)172			{173				return propertyInfo;174			}175			return bestMatch;176		}177		/// <summary>178		///   Attributes can only accept simple types, so we return null for null,179		///   if the value is passed as string we call to string (should help with converting), 180		///   otherwise, we use the value as is (enums, integer, etc).181		/// </summary>182		private static object ConvertValue(object obj, Type paramType)183		{184			if (obj == null)185			{186				return null;187			}188			if (paramType == typeof(String))189			{190				return obj.ToString();191			}192			return obj;193		}194		private static object GetDefaultValueFor(ParameterInfo parameter)195		{196			var type = parameter.ParameterType;197			if (type == typeof(bool))198			{199				return false;200			}201			if (type.IsEnum)202			{203				return Enum.ToObject(type, 0);204			}205			if (type == typeof(char))206			{207				return Char.MinValue;208			}209			if (type.IsPrimitive)210			{211				return 0;212			}213			if(type.IsArray && parameter.IsDefined(typeof(ParamArrayAttribute), true))214			{215				return Array.CreateInstance(type.GetElementType(), 0);216			}217			return null;218		}219		private static List<PropertyInfo> GetPropertyCandidates(Type attributeType)220		{221			var propertyCandidates = new List<PropertyInfo>();222			foreach (var pi in attributeType.GetProperties(BindingFlags.Instance | BindingFlags.Public))223			{224				if (pi.CanRead && pi.CanWrite)225				{226					propertyCandidates.Add(pi);227				}228			}229			return propertyCandidates;230		}231		private static bool AreAttributeElementsEqual(object first, object second)232		{233			//we can have either System.Type, string or numeric type234			if (first == null)235			{236				return second == null;237			}238			//let's try string239			var firstString = first as string;240			if (firstString != null)241			{242				return AreStringsEqual(firstString, second as string);243			}244			//by now we should only be left with numeric types245			return first.Equals(second);246		}247		private static bool AreStringsEqual(string first, string second)248		{249			Debug.Assert(first != null, "first != null");250			return first.Equals(second, StringComparison.Ordinal);251		}252		public bool Equals(AttributeDisassembler other)253		{254			return !ReferenceEquals(null, other);255		}256		public override bool Equals(object obj)257		{258			if (ReferenceEquals(null, obj))259			{260				return false;261			}262			if (ReferenceEquals(this, obj))263			{264				return true;265			}266			if (obj.GetType() != typeof(AttributeDisassembler))267			{268				return false;269			}270			return Equals((AttributeDisassembler)obj);271		}272		public override int GetHashCode()273		{274			return GetType().GetHashCode();275		}276	}277}...

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;7using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;8using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;9using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;10{11    {12        static void Main(string[] args)13        {14            var attributeDisassembler = new AttributeDisassembler();15            var type = typeof(MyClass);16            var attributes = type.GetCustomAttributes(true);17            foreach (var attribute in attributes)18            {19                var attributeBuilder = new AttributeBuilder(attribute.GetType());20                var attributeProperties = attribute.GetType().GetProperties();21                foreach (var attributeProperty in attributeProperties)22                {23                    var value = attributeProperty.GetValue(attribute);24                    attributeBuilder.SetNamedArgument(attributeProperty.Name, new ConstReference(value));25                }26                attributeDisassembler.AddAttribute(attributeBuilder);27            }28            var assembly = new AssemblyGenerator("MyAssembly");29            var module = new ModuleGenerator(assembly, "MyModule");30            var classEmitter = new ClassEmitter(module, "MyClass", TypeAttributes.Public);31            classEmitter.AddAttribute(attributeDisassembler);32            var method = classEmitter.CreateMethod("MyMethod", MethodAttributes.Public, typeof(void));33            method.GetILGenerator().Emit(OpCodes.Ret);34            classEmitter.CreateType();35            assembly.Save("MyAssembly.dll");36        }37    }38    [AttributeUsage(AttributeTargets.Class)]39    {40        public string MyProperty { get; set; }41    }42    [MyClass(MyProperty = "MyValue")]43    {44        public void MyMethod()45        {46        }47    }48}

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Reflection;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5    {6        static void Main(string[] args)7        {8            AttributeDisassembler disassembler = new AttributeDisassembler();9            byte[] bytes = disassembler.Disassemble(typeof(CustomAttribute).Module);10            Assembly asm = Assembly.Load(bytes);11            Type type = asm.GetType("ConsoleApplication1.CustomAttribute");12            Console.WriteLine(type);13            Console.Read();14        }15    }16    [AttributeUsage(AttributeTargets.All)]17    {18    }19}20using System;21using System.Reflection;22using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;23{24    {25        static void Main(string[] args)26        {27            AttributeDisassembler disassembler = new AttributeDisassembler();28            byte[] bytes = disassembler.Disassemble(typeof(CustomAttribute).Module);29            Assembly asm = Assembly.Load(bytes);30            Type type = asm.GetType("ConsoleApplication1.CustomAttribute");31            Console.WriteLine(type);32            Console.Read();33        }34    }35    [AttributeUsage(AttributeTargets.All)]36    {37    }38}39using System;40using System.Reflection;41using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;42{43    {44        static void Main(string[] args)45        {46            AttributeDisassembler disassembler = new AttributeDisassembler();47            byte[] bytes = disassembler.Disassemble(typeof(CustomAttribute).Module);48            Assembly asm = Assembly.Load(bytes);49            Type type = asm.GetType("ConsoleApplication1.CustomAttribute");50            Console.WriteLine(type);51            Console.Read();52        }53    }54    [AttributeUsage(AttributeTargets.All)]

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Reflection;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5    {6        public static void Main(string[] args)7        {8            AttributeDisassembler ad = new AttributeDisassembler();9            MethodInfo mi = typeof(Program).GetMethod("Test");10            Attribute[] attrs = ad.GetAttributes(mi);11            Console.WriteLine(attrs.Length);12            Console.ReadLine();13        }14        public void Test()15        {16        }17    }18}

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Reflection;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5    {6        public static void Main(string[] args)7        {8            AttributeDisassembler disassembler = new AttributeDisassembler();9            var attr = disassembler.GetAttribute(typeof(ExampleAttribute), typeof(ExampleAttribute).GetTypeInfo().Assembly);10            Console.WriteLine(attr);11        }12    }13    [AttributeUsage(AttributeTargets.All)]14    {15        public string Name { get; set; }16        public string Value { get; set; }17    }18}19[AttributeUsage(AttributeTargets.All)]20    {21        public string Name { get; set; }22        public string Value { get; set; }23        public int Age { get; set; }24        public string Address { get; set; }25    }26[AttributeUsage(AttributeTargets.All)]27    {28        public string Name { get; set; }29        public string Value { get; set; }30        public int Age { get; set; }31        public string Address { get; set; }32        public string City { get; set; }33    }

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;7{8    {9        public virtual void Foo() { }10    }11    {12        public override void Foo()13        {14            base.Foo();15        }16    }17    {18        static void Main(string[] args)19        {20            var attributeDisassembler = new AttributeDisassembler();21            var attribute = attributeDisassembler.Disassemble(typeof(B));22            Console.WriteLine(attribute);23        }24    }25}26[GeneratedCode("Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST.SimpleASTGenerator, Telerik.JustMock.Core.Castle.DynamicProxy", "

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Reflection;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5    {6        static void Main(string[] args)7        {8            var methodInfo = typeof(Program).GetMethod("Test");9            var attrDisassembler = new AttributeDisassembler(methodInfo);10            var attr = attrDisassembler.GetAttributes();11            foreach (var item in attr)12            {13                Console.WriteLine(item.AttributeType);14            }15        }16        public void Test()17        {18        }19    }20}

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System.Reflection;2using System;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5    public static void Main()6    {7        var assembly = Assembly.LoadFile(@"C:\Users\Public\Documents\Telerik\JustMock\Examples\DynamicProxy\bin\Debug\DynamicProxy.dll");8        var type = assembly.GetType("DynamicProxy.MyClass");9        var disassembler = new AttributeDisassembler(type);10        var result = disassembler.Disassemble();11        Console.WriteLine(result);12    }13}14[module: System.Runtime.CompilerServices.CompilerGeneratedAttribute()]15[module: System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5.2", FrameworkDisplayName = "")]16[module: System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]17[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("DynamicProxy.Tests, PublicKey=002400000480000094000000060200000024

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;2using System.Reflection;3using System.Reflection.Emit;4{5    {6        public void Method1()7        {8            var assembly = Assembly.GetExecutingAssembly();9            var module = assembly.GetModules()[0];10            var type = module.GetTypes()[0];11            var method = type.GetMethods()[0];12            var attributeDisassembler = new AttributeDisassembler(method);13            var attributes = attributeDisassembler.GetAttributes();14            var attribute = attributes[0];15            var constructor = attribute.GetConstructor();16            var parameters = constructor.GetParameters();17            var parameter = parameters[0];18            var parameterType = parameter.ParameterType;19        }20    }21}

Full Screen

Full Screen

AttributeDisassembler

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;7using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;8using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;9using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST.Impl;10{11    {12        static void Main(string[] args)13        {14            var method = typeof(Program).GetMethod("Main");15            var attributes = method.GetCustomAttributesData();16            var disassembler = new AttributeDisassembler();17            var result = disassembler.Disassemble(attributes);18            Console.WriteLine(result);19        }20    }21}22[AttributeDisassemblerTestAttribute("Test", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)]23[AttributeDisassemblerTestAttribute(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)]24[AttributeDisassemblerTestAttribute(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)]25[AttributeDisassemblerTestAttribute(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful