Best JustMockLite code snippet using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.AttributeDisassembler.Disassemble
AttributeDisassembler.cs
Source:AttributeDisassembler.cs
...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}...
Disassemble
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;6using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;7using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;8using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.CodeBuilders;9using System.Reflection.Emit;10using System.Reflection;11using System.Collections;12using System.IO;13{14 {15 static void Main(string[] args)16 {17 var moduleScope = new ModuleScope();18 var type = typeof(Example);19 var method = type.GetMethod("Method");20 var methodBuilder = new MethodBuilder(method, moduleScope);21 var methodInfo = typeof(Example).GetMethod("Method");22 var parameters = methodInfo.GetParameters();23 var parametersTypes = parameters.Select(p => p.ParameterType).ToArray();24 var methodInfoForCall = typeof(Example).GetMethod("Method", parametersTypes);25 var methodCall = new MethodCallExpression(methodInfoForCall, new ThisReferenceExpression(type), new ArgumentReferenceExpression(parameters[0].ParameterType, 0));26 var returnStatement = new ReturnStatement(methodCall);27 methodBuilder.CodeBuilder.AddStatement(returnStatement);28 var attribute = new ExampleAttribute("test");29 var attributeDisassembler = new AttributeDisassembler(attribute);30 var attributeBuilder = attributeDisassembler.Disassemble();31 methodBuilder.DefineCustomAttribute(attributeBuilder);32 var typeBuilder = new TypeBuilder(type, moduleScope);33 typeBuilder.DefineMethod(methodBuilder);34 var typeInfo = typeBuilder.CreateType();35 var instance = Activator.CreateInstance(typeInfo);36 var methodInfoForInvoke = typeInfo.GetMethod("Method");37 var parametersForInvoke = methodInfoForInvoke.GetParameters();38 var parametersTypesForInvoke = parametersForInvoke.Select(p => p.ParameterType).ToArray();39 var methodInfoForInvoke2 = typeInfo.GetMethod("Method", parametersTypesForInvoke);40 var value = methodInfoForInvoke2.Invoke(instance, new object[] { "test" });41 Console.WriteLine(value);42 }43 }44 {45 public string Method(string str)46 {47 return str;48 }49 }50 [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
Disassemble
Using AI Code Generation
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 static void Main(string[] args)10 {11 AttributeDisassembler disassembler = new AttributeDisassembler();12 byte[] bytes = disassembler.Disassemble(typeof(AssemblyInfo).Assembly);13 foreach (byte b in bytes)14 {15 Console.Write(b);16 }17 Console.ReadLine();18 }19 }20}21using System;22using System.Collections.Generic;23using System.Linq;24using System.Text;25using System.Threading.Tasks;26using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;27{28 {29 static void Main(string[] args)30 {31 AttributeDisassembler disassembler = new AttributeDisassembler();32 byte[] bytes = disassembler.Disassemble(typeof(AssemblyInfo).Assembly);33 foreach (byte b in bytes)34 {35 Console.Write(b);36 }37 Console.ReadLine();38 }39 }40}41using System;42using System.Collections.Generic;43using System.Linq;44using System.Text;45using System.Threading.Tasks;46using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;47{48 {49 static void Main(string[] args)50 {51 AttributeDisassembler disassembler = new AttributeDisassembler();52 byte[] bytes = disassembler.Disassemble(typeof(AssemblyInfo).Assembly);53 foreach (byte b in bytes)54 {55 Console.Write(b);56 }57 Console.ReadLine();58 }59 }60}61using System;62using System.Collections.Generic;63using System.Linq;64using System.Text;65using System.Threading.Tasks;66using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;67{68 {69 static void Main(string[] args
Disassemble
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Reflection;6using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;7using Telerik.JustMock.Core.Castle.DynamicProxy;8{9 {10 static void Main(string[] args)11 {12 var assembly = typeof(ProxyGenerator).Assembly;13 var type = assembly.GetType("Telerik.JustMock.Core.Castle.DynamicProxy.Generators.AttributeDisassembler");14 var methodInfo = type.GetMethod("Disassemble", BindingFlags.Static | BindingFlags.NonPublic);15 var attribute = new CustomAttributeBuilder(typeof(ObsoleteAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { "Obsolete" });16 var result = methodInfo.Invoke(null, new object[] { attribute });17 Console.WriteLine(result);18 Console.ReadLine();19 }20 }21}22using System;23using System.Collections.Generic;24using System.Linq;25using System.Text;26using System.Reflection;27using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;28using Telerik.JustMock.Core.Castle.DynamicProxy;29{30 {31 static void Main(string[] args)32 {33 var assembly = typeof(ProxyGenerator).Assembly;34 var type = assembly.GetType("Telerik.JustMock.Core.Castle.DynamicProxy.Generators.AttributeDisassembler");35 var methodInfo = type.GetMethod("GetCustomAttributes", BindingFlags.Static | BindingFlags.NonPublic);36 var attribute = new CustomAttributeBuilder(typeof(ObsoleteAttribute).GetConstructor(new Type[] { typeof(string) }), new object[] { "Obsolete" });37 var result = methodInfo.Invoke(null, new object[] { attribute });38 Console.WriteLine(result);39 Console.ReadLine();40 }41 }42}43using System;44using System.Collections.Generic;45using System.Linq;46using System.Text;47using System.Reflection;48using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;49using Telerik.JustMock.Core.Castle.DynamicProxy;50{51 {52 static void Main(string[] args)
Disassemble
Using AI Code Generation
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 string str = disassembler.Disassemble(typeof(JustMockTest.Program).Assembly);10 Console.WriteLine(str);11 }12 }13}14using System;15using System.Reflection;16using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;17{18 {19 static void Main(string[] args)20 {21 AttributeDisassembler disassembler = new AttributeDisassembler();22 string str = disassembler.Disassemble(typeof(JustMockTest.Program).Assembly);23 Console.WriteLine(str);24 }25 }26}27using System;28using System.Reflection;29using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;30{31 {32 static void Main(string[] args)33 {34 AttributeDisassembler disassembler = new AttributeDisassembler();35 string str = disassembler.Disassemble(typeof(JustMockTest.Program).Assembly);36 Console.WriteLine(str);37 }38 }39}40using System;41using System.Reflection;42using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;43{44 {45 static void Main(string[] args)46 {47 AttributeDisassembler disassembler = new AttributeDisassembler();48 string str = disassembler.Disassemble(typeof(JustMockTest.Program).Assembly);49 Console.WriteLine(str);50 }51 }52}53using System;54using System.Reflection;55using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
Disassemble
Using AI Code Generation
1using System;2using System.Reflection;3using Telerik.JustMock.Core;4using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;5{6 [AttributeUsage(AttributeTargets.All)]7 {8 public string MyProperty { get; set; }9 }10 {11 public virtual int Bar()12 {13 return 42;14 }15 }16 {17 public static void Main()18 {19 var foo = Mock.Create<Foo>();20 var method = foo.GetType().GetMethod("Bar");21 var attributes = method.GetCustomAttributes(false);22 foreach (var attribute in attributes)23 {24 var customAttribute = (MyAttribute)attribute;25 Console.WriteLine("Custom Attribute: {0}", customAttribute.MyProperty);26 }27 var disassembler = new AttributeDisassembler();28 var attributeBuilder = disassembler.Disassemble(method);29 var attribute = attributeBuilder.CreateAttribute();30 Console.WriteLine("Custom Attribute: {0}", ((MyAttribute)attribute).MyProperty);31 }32 }33}
Disassemble
Using AI Code Generation
1using System;2using System.Reflection;3using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;4{5 {6 static void Main(string[] args)7 {8 Type attributeType = typeof(System.Diagnostics.DebuggerHiddenAttribute);9 ConstructorInfo attributeConstructor = attributeType.GetConstructor(new Type[] { });10 Attribute attribute = (Attribute)attributeConstructor.Invoke(new object[] { });11 AttributeDisassembler disassembler = new AttributeDisassembler(attribute);12 CustomAttributeBuilder builder = disassembler.Disassemble();13 Type attributeType1 = builder.GetType();14 ConstructorInfo attributeConstructor1 = attributeType1.GetConstructor(new Type[] { });15 Attribute attribute1 = (Attribute)attributeConstructor1.Invoke(new object[] { });16 AttributeDisassembler disassembler1 = new AttributeDisassembler(attribute1);17 CustomAttributeBuilder builder1 = disassembler1.Disassemble();18 Type attributeType2 = builder1.GetType();19 ConstructorInfo attributeConstructor2 = attributeType2.GetConstructor(new Type[] { });20 Attribute attribute2 = (Attribute)attributeConstructor2.Invoke(new object[] { });21 AttributeDisassembler disassembler2 = new AttributeDisassembler(attribute2);22 CustomAttributeBuilder builder2 = disassembler2.Disassemble();23 Type attributeType3 = builder2.GetType();24 ConstructorInfo attributeConstructor3 = attributeType3.GetConstructor(new Type[] { });25 Attribute attribute3 = (Attribute)attributeConstructor3.Invoke(new object[] { });26 AttributeDisassembler disassembler3 = new AttributeDisassembler(attribute3);27 CustomAttributeBuilder builder3 = disassembler3.Disassemble();28 Type attributeType4 = builder3.GetType();
Disassemble
Using AI Code Generation
1using System;2using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;3using System.Reflection;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static void Main(string[] args)11 {12 var assembly = Assembly.Load("Telerik.JustMock.Core");13 var type = assembly.GetType("Telerik.JustMock.Core.Castle.DynamicProxy.Generators.AttributeDisassembler");14 var method = type.GetMethod("Disassemble");15 var attribute = method.GetCustomAttributes(typeof(System.Runtime.InteropServices.ComVisibleAttribute), false);16 Console.WriteLine(attribute.Length);17 Console.ReadLine();18 }19 }20}
Disassemble
Using AI Code Generation
1using System;2using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;3{4 {5 public static void Main(string[] args)6 {7 var attribute = new System.Runtime.CompilerServices.CompilerGeneratedAttribute();8 var code = AttributeDisassembler.Disassemble(attribute);9 Console.WriteLine(code);10 }11 }12}13[assembly: System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!