public void ProcessGraph() { foreach (MethodInfo item in typeof(Process).GetMethods()) { MyAttribute attr = (MyAttribute)Attribute.GetCustomAttribute(item, typeof(MyAttribute)); if (attr != null) { //object o = typeof(Process).InvokeMember(item.Name, BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null); } } object o = Activator.CreateInstance(typeof(Process)); foreach (FieldInfo item in typeof(Process).GetFields()) { MyAttribute attr = (MyAttribute)Attribute.GetCustomAttribute(item, typeof(MyAttribute)); if (attr != null) { if (attr.PositionalString == "Atom1") { MethodInfo mi = item.FieldType.GetMethods().FirstOrDefault(x => x.Name == "Compile"); object[] param = new object[1]; param[0] = 5; int x2 = (int)mi.Invoke(o, param); } //ParameterInfo[] pis = mi.GetParameters(); //int i = (int) mi.Invoke(System.Linq.Expressions.Expression.Bind( } } }
public void TestMethod7() { MyFile file = TestDataStorage.GetFile("Private File", userStoryId); MyAttribute attribute = TestDataStorage.GetAttribute("Attribute XXX", userStoryId); Debug.WriteLine(userStoryId + " - TestMethod7"); }
public static void Main() { // Get the set of custom attributes associated with the type Object[] TypeAttrs = typeof(App).GetCustomAttributes(false); Console.WriteLine("Number of custom attributes on Application type: " + TypeAttrs.Length); for (int n = 0; n < TypeAttrs.Length; n++) { MyAttribute.DisplayAttrInfo(n, (Attribute)TypeAttrs[n]); } // Get the set of methods associated with the type MemberInfo[] mi = typeof(App).FindMembers( MemberTypes.Constructor | MemberTypes.Method, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly, Type.FilterName, "*"); Console.WriteLine("Number of methods (includes constructors): " + mi.Length); for (int x = 0; x < mi.Length; x++) { // Get the set of custom attributes associated with this method Object[] MethodAttrs = mi[x].GetCustomAttributes(false); Console.WriteLine("Method name: " + mi[x].Name + "\t(" + MethodAttrs.Length + " attributes)"); for (int n = 0; n < MethodAttrs.Length; n++) { Console.Write(" "); MyAttribute.DisplayAttrInfo(n, (Attribute)MethodAttrs[n]); } } // Test the ObsoleteAttribute type new OldType(); }
public void SaveFolderTest_Fail(string dataKey, string exceptionMsgKey) { try { string testCaseId = "TC200"; Service service = new Service(); using (LiteDatabaseHelper db = new LiteDatabaseHelper()) { // Prepare Test Data Folder result; Folder folder = TestDataStorage.GetFolder("Folder Origin", userStoryId, testCaseId); MyAttribute invalidAttribute = TestDataStorage.GetAttribute(dataKey, userStoryId, testCaseId); // Given: I has existed folder (*) with known id in database Guid id = db.Folder.Insert(folder).AsGuid; // And: I have added invalid attribute folder.Attributes.Add(invalidAttribute); // When: I save it by using method SaveFolder result = service.SaveFolder(folder, folder.Id); Assert.Fail(); } } catch (Exception ex) { // Then: It throw exception based on invalid type Assert.AreEqual(ex.Message, ExceptionMessages.AttributeExceptionMessages[exceptionMsgKey]); } }
public static int Main() { Type myHelloworld = MyCreateCallee(Thread.GetDomain()); ConstructorInfo myConstructor = myHelloworld.GetConstructor(new Type[] { typeof(String) }); object[] myAttributes1 = myConstructor.GetCustomAttributes(true); if (myAttributes1 == null) { return(1); } if (myAttributes1.Length != 1) { return(2); } MyAttribute myAttribute = myAttributes1[0] as MyAttribute; if (myAttribute == null) { return(3); } if (myAttribute.my.GetType() != typeof(TypeCode)) { return(4); } return(0); }
public static void Main1() { // Get type Type type = typeof(Program); // Get custom attribute applied to type's methods MyAttribute att = null; foreach (MethodInfo mi in type.GetMethods()) { if ((att = (MyAttribute) Attribute.GetCustomAttribute(mi, typeof(MyAttribute), false)) != null) { Console.WriteLine("Found attribute {0} in method {1}: " + "att.Info = {2}", typeof(MyAttribute), mi.ToString(), att.Info); } } // Se for para obter um atributo de um dado membro usar: MethodInfo meth = type.GetMethod("M"); //att = (MyAttribute)meth.GetCustomAttribute(typeof(MyAttribute), false); // Ou: att = (MyAttribute)meth.GetCustomAttribute <MyAttribute>(false); if (att != null) { Console.WriteLine("Found attribute {0} in method {1}: " + "att.Info = {2}", typeof(MyAttribute), meth.ToString(), att.Info); } }
public static MyAttribute GetAttribute(string dataKey, string userStoryId, string testCaseId = "shared") { JsonTestDataReader reader = new JsonTestDataReader(userStoryId, testCaseId, dataKey); MyAttribute attribute = reader.GetTestData <MyAttribute>(); return(attribute); }
public TreeNode(string name, int tableIndex, MyAttribute nodeAttribute, string inEdge) { Name = name; TableIndex = tableIndex; NodeAttribute = nodeAttribute; ChildNodes = new List <TreeNode>(); Edge = inEdge; }
public void GetAttributeReturnsNullIfMultipleFound() { bool inherit = false; MyAttribute attrib = new MyAttribute(); MockAttributeProvider provider = new MockAttributeProvider(new object[]{ attrib, attrib }, inherit); MyAttribute result = ReflectionHelper.GetAttribute<MyAttribute>(provider, inherit); Assert.IsNull(result); }
public void GetAttributeReturnsOnlyIfOneIsPresent() { bool inherit = false; MyAttribute attrib = new MyAttribute(); MockAttributeProvider provider = new MockAttributeProvider(new object[] { attrib }, inherit); MyAttribute result = ReflectionHelper.GetAttribute<MyAttribute>(provider, inherit); Assert.AreSame(attrib,result); }
public void GetAttributeReturnsNullIfMultipleFound() { const bool inherit = false; MyAttribute attrib = new MyAttribute(); MockAttributeProvider provider = new MockAttributeProvider(new object[] { attrib, attrib }, inherit); MyAttribute result = ReflectionHelper.GetAttribute <MyAttribute>(provider, inherit); Assert.IsNull(result); }
public void GetAttributeReturnsOnlyIfOneIsPresent() { const bool inherit = false; MyAttribute attrib = new MyAttribute(); MockAttributeProvider provider = new MockAttributeProvider(new object[] { attrib }, inherit); MyAttribute result = ReflectionHelper.GetAttribute <MyAttribute>(provider, inherit); Assert.AreSame(attrib, result); }
public void FindFirstCustomAttribute() { ArrayList expectedValues = new ArrayList(new int[] { 12, 34, 56 }); Method method = JsonRpcServices.GetClassFromType(typeof(TestService)).GetMethodByName("Foo"); MyAttribute attribute = (MyAttribute)method.FindFirstCustomAttribute(typeof(MyAttribute)); expectedValues.Remove(attribute.TestValue); Assert.AreEqual(2, expectedValues.Count); }
public ActionResult Create([Bind(Include = "ID,AttributName,TypeID")] MyAttribute attribute) { if (ModelState.IsValid) { Meneger.Meneger.SaveDB(attribute); return(RedirectToAction("Index")); } ViewBag.TypeID = new SelectList(context.AttributesTypes, "ID", "AttributeType", attribute.TypeID); return(View(attribute)); }
public void EmptyNonOverridenGetHashCode () { MyAttribute a1 = new MyAttribute (); MyAttribute a2 = new MyAttribute (); Assert.AreEqual (a1.GetHashCode (), a2.GetHashCode (), "identical argument-less"); Assert.AreEqual (a1.GetHashCode (), a1.TypeId.GetHashCode (), "Empty/TypeId"); MySubAttribute b1 = new MySubAttribute (); Assert.AreNotEqual (a1.GetHashCode (), b1.GetHashCode (), "non-identical-types"); Assert.AreEqual (b1.GetHashCode (), b1.TypeId.GetHashCode (), "Empty/TypeId/Sub"); }
public void GetAttributesReturnsOnlyOne() { const bool inherit = false; MyAttribute attrib = new MyAttribute(); object[] attribs = { attrib }; MockAttributeProvider provider = new MockAttributeProvider(attribs, inherit); MyAttribute[] result = ReflectionHelper.GetAttributes <MyAttribute>(provider, inherit); Assert.AreEqual(attribs.Length, result.Length); }
public void GetAttributesReturnsNotEmpty() { bool inherit = false; MyAttribute attrib = new MyAttribute(); object[] attribs = new object[] { attrib, attrib }; MockAttributeProvider provider = new MockAttributeProvider(attribs, inherit); MyAttribute[] result = ReflectionHelper.GetAttributes <MyAttribute>(provider, inherit); Assert.AreEqual <int>(attribs.Length, result.Length); }
// With a few different instances of this class in the scene, we can see that they can all share the same attribute over different functions. void Start() { // this creates 10 BaseClass objects and adds them to an array. BaseClass[] baseClasses = new BaseClass[10]; for (int i = 0; i < 10; i++) { BaseClass bc = new BaseClass(i.ToString()); baseClasses [i] = bc; } // we need to look at the class, find all the functions in the classes, get the attributes of those functions, and then add the function the UpdateEvent. // First we begin by getting each object // We look into our array of found objects and then get the type of the object. This allows us to get the methods from t with the GetMethods() reflection function. // This turns into a MethodInfo[] array, where we can sort through each one and look for attributes. foreach (object o in baseClasses) { Type t = o.GetType(); MethodInfo[] methods = t.GetMethods(); foreach (MethodInfo method in methods) { object[] attributes = method.GetCustomAttributes(true); // we look at the object's custom attributes assigned to the object[] attributes variable. // Now that we have an array of attributes for each method, we need to look at each attribute foreach (object attribute in attributes) { if (attribute is MyAttribute) // check to see if this is the attribute that we expect, e.g. MyAttribute { MyAttribute ma = attribute as MyAttribute; //MyAttribute ma = (MyAttribute) attribute; if (ma.Name == "Update") // if ma is named "Update" then we'll add the method we started looking at to the event. { EventInfo ei = typeof(SpecialAttributes).GetEvent("UpdateEvent"); // first, we need to get the EventInfo of the event we're assigning it to Type et = ei.EventHandlerType; // second, we get the type from ei, where the EventHandlerType is the UpdateHandler which the UpdateEvent is assigned to. Delegate d = Delegate.CreateDelegate(et, o, method); // each function found in the object of the correct type gets a new delegate assigned to it // CreateDelegate() takes 3 args - 1. the type it's creating a delegate for, 2. what owns the function we're assigning to that event // 3. what function is being assigned to the event, e.g. function we scanned for MethodInfo method attributes. ei.AddEventHandler(this, d); // assign Delegate d to EventInfo we got from SpecialAttributes class ei by using AddEventHandler() // first arg is the object that the event is assigned to, this assigns the class to itself as the object // the callback assigned to this object is Delegate d. // Now when the game is run, objects are created. // After they are created, they are scanned for functions that // have attributes. IF the attribute's name is "Updated", then the function is assigned to the UpdateEvent // which is called from MonoBehaviour's Update(). // This sort of utility allows for a great number of simple ways to connect classes together. Better interobject // communication allows for your code to more intelligently. // This might not be the best way to operate a scene. It is brute force. A more simple method would be to use // eventHandler += object.OnUpdate(); // However, in a situation where you can't create the scene manager before the objects, something like this might be more useful. } } } } } }
// Entry point of the program public static void Main(string[] Args) { Console.WriteLine(SayHello1("Hello to Me 1")); Console.WriteLine(SayHello2("Hello to Me 2")); Func <string, string> action1 = SayHello1; Func <string, string> action2 = SayHello2; MyAttribute myAttribute1 = (MyAttribute)Attribute.GetCustomAttribute(action1.Method, typeof(MyAttribute)); MyAttribute myAttribute2 = (MyAttribute)Attribute.GetCustomAttribute(action2.Method, typeof(MyAttribute)); Console.ReadLine(); }
public void CustomAttributesInheritanceTest(int paramIndex, bool exists, int expectedMyAttributeValue) { ParameterInfo parameterInfo = GetParameterInfo(typeof(DerivedParameterInfoMetadata), "VirtualMethodWithCustomAttributes", paramIndex); CustomAttributeData attribute = parameterInfo.CustomAttributes.SingleOrDefault(a => a.AttributeType.Equals(typeof(MyAttribute))); Assert.Equal(exists, attribute != null); ICustomAttributeProvider prov = parameterInfo as ICustomAttributeProvider; MyAttribute myAttribute = prov.GetCustomAttributes(typeof(MyAttribute), true).SingleOrDefault() as MyAttribute; Assert.Equal(exists, myAttribute != null); Assert.Equal(expectedMyAttributeValue, exists ? myAttribute.Value : expectedMyAttributeValue); }
public static test() { Assembly a=Assembly.Load("程序集"); //反射获取特性 Type type =typeof(Wriken); MyAttribute M1= (MyAttribute)type.GetCustomAttribute(typeof(MyAttribute).true); //加载反射数据库类 Type t1=a.Gettype(M1.show()); //实例化反射对象 利用接口接收 UsageDb o=(UsageDb)Activator.CreateInstance(t1); o.use(); }
public static void DisplayAttrInfo(int n, Attribute a) { if (a is MyAttribute) { // Refer to the one of the custom attributes MyAttribute myAttribute = (MyAttribute)a; Console.WriteLine("{0}-\"{1}\": {2}", n, a, "X: " + myAttribute.x + ", Y: " + myAttribute.y + ", S: " + myAttribute.s); } else { Console.WriteLine("{0}-\"{1}\"", n, a); } }
public static void SaveDB(MyAttribute attribute) { using (BooksCatalogueEntities1 Db = new BooksCatalogueEntities1()) { Entity.Attribute atrDb = new Entity.Attribute(); atrDb.AttributesType = attribute.AttributesType; atrDb.AttributName = attribute.AttributName; atrDb.AttributValues = attribute.AttributValues; atrDb.ID = attribute.ID; atrDb.TypeID = attribute.TypeID; Db.Attributes.Add(atrDb); Db.SaveChanges(); } }
public static void Main1() { MyAttribute att = null; foreach (MethodInfo mi in typeof(Program).GetMethods()) { if ((att = (MyAttribute) Attribute.GetCustomAttribute(mi, typeof(MyAttribute), false)) != null) { Console.WriteLine("Found attribute {0} in method {1}: " + "att.Info = {2}", typeof(MyAttribute), mi.ToString(), att.Info); } } }
public static bool AreEqualAttributes(MyAttribute myAttribute1, MyAttribute myAttribute2) { if (myAttribute1 == null && myAttribute2 == null) { return(true); } if (myAttribute1 == null || myAttribute2 == null) { return(false); } return(string.Equals(myAttribute1.Name, myAttribute2.Name) && myAttribute1.Type == myAttribute2.Type && string.Equals(myAttribute1.Value, myAttribute2.Value)); }
private void Compare(MyAttribute existingAttribute, MyAttribute newAttribute, List <SymbolMismatch> symbols) { Compare(existingAttribute.Name, newAttribute.Name, symbols, existingAttribute, newAttribute, MismatchReason.AttributeMismatch); if (newAttribute.Values.Count != existingAttribute.Values.Count) { AddMismatch(symbols, existingAttribute, newAttribute, MismatchReason.AttributeMismatch); return; } foreach (var value in existingAttribute.Values) { var correspondingAttribute = newAttribute.Values.FirstOrDefault(x => x.Key == value.Key); Compare(value.Value, correspondingAttribute.Value, symbols, existingAttribute, newAttribute, MismatchReason.AttributeMismatch); } }
public static void Main(string[] args) { System.Reflection.MethodInfo mi = typeof(Program).GetMethod("bar", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); object[] attrs = mi.GetCustomAttributes(true); foreach (object attr in attrs) { MyAttribute authAttr = attr as MyAttribute; if (authAttr != null) { System.Console.WriteLine(authAttr.Name); } } }
private MyAttribute GetAttribute(CustomAttributeData attributeData, ISymbol parent) { var values = new Dictionary <string, string>(); foreach (var namedArgument in attributeData.NamedArguments) { values.Add(namedArgument.MemberName, namedArgument.TypedValue.Value.ToString()); } var attribute = new MyAttribute(attributeData.AttributeType.Name, values) { Parent = parent }; return(attribute); }
///// <summary> ///// if it's leaf, add childNodes ///// </summary> ///// <param name="root"></param> ///// <param name="data">current table; not necessaryly the original table</param> ///// <param name="valToCheck"></param> ///// <returns></returns> //private static bool CheckIfIsLeaf_sealIfLeaf(DataTable data, TreeNode root, string valToCheck) //{ // var isLeaf = true; // var allEndValues = new List<string>(); // // get all leaf values for the attribute in question // for (var i = 0; i < data.Rows.Count; i++) // { // if (data.Rows[i][root.TableIndex].ToString().Equals(valToCheck)) // { // allEndValues.Add(data.Rows[i][data.Columns.Count - 1].ToString()); // } // } // // check whether all elements of the list have the same value // if (allEndValues.Count > 0 && allEndValues.Any(x => x != allEndValues[0])) // { // isLeaf = false; // } // // create leaf with value to display and edge to the leaf // if (isLeaf) // { // root.ChildNodes.Add(new TreeNode(true, allEndValues[0], valToCheck)); // } // return isLeaf; //} private static TreeNode __GetRootNodeFroClass_tblAssumeDwelt(DataTable data, string inEdge) { var lastIndex = data.Columns.Count - 1; return(new TreeNode( data.Columns[data.Columns.Count - 1].ColumnName , lastIndex , new MyAttribute( data.Columns[lastIndex].ToString() , MyAttribute.GetDifferentAttributeNamesOfColumn(data, lastIndex) ), inEdge )); }
public void CustomAttributes() { MyAttribute attribute; Attribute[] attributes; attribute = new MyAttribute(); _builder.AddCustomAttribute(attribute); attributes = _builder.GetCustomAttributes(); Assert.AreEqual(1, attributes.Length); Assert.AreSame(attribute, attributes[0]); attribute = new MyAttribute(); _builder.AddCustomAttribute(attribute); attributes = _builder.GetCustomAttributes(); Assert.AreEqual(2, attributes.Length); Assert.AreSame(attribute, attributes[1]); }
private void RefreshShowedAttributes(object sender) { MyAttribute attribute = sender as MyAttribute; switch (attribute.Name) { case "Type": OnPropertyChanged("TypeAttribute"); UserSettingsHelper.WriteToUserSettings("TypeAttribute", this.AttributesList[0].CheckedStatus); break; case "Status": OnPropertyChanged("StatusAttribute"); UserSettingsHelper.WriteToUserSettings("StatusAttribute", this.AttributesList[1].CheckedStatus); break; case "Created": OnPropertyChanged("CreatedAttribute"); UserSettingsHelper.WriteToUserSettings("CreatedAttribute", this.AttributesList[2].CheckedStatus); break; case "Updated": OnPropertyChanged("UpdatedAttribute"); UserSettingsHelper.WriteToUserSettings("UpdatedAttribute", this.AttributesList[3].CheckedStatus); break; case "Assignee": OnPropertyChanged("AssigneeAttribute"); UserSettingsHelper.WriteToUserSettings("AssigneeAttribute", this.AttributesList[4].CheckedStatus); break; case "Summary": OnPropertyChanged("SummaryAttribute"); UserSettingsHelper.WriteToUserSettings("SummaryAttribute", this.AttributesList[5].CheckedStatus); break; case "Priority": OnPropertyChanged("PriorityAttribute"); UserSettingsHelper.WriteToUserSettings("PriorityAttribute", this.AttributesList[6].CheckedStatus); break; } }
private static TreeNode GetRootNode_tblAssumeDefiniteAttrsPurged(DataTable data, string inEdge) { ///if there is only one col: the class . /// if (data.Columns.Count == 1) { return(__GetRootNodeFroClass_tblAssumeDwelt(data, inEdge)); } var attributes = new List <MyAttribute>(); var highestInformationGainIndex = -1; var highestInformationGain = double.MinValue; // Get all names, amount of attributes and attributes for every column for (var i = 0; i < data.Columns.Count - 1; i++) { var differentAttributenames = MyAttribute.GetDifferentAttributeNamesOfColumn(data, i); attributes.Add(new MyAttribute(data.Columns[i].ToString(), differentAttributenames)); } // Calculate Entropy (S) var tableEntropy = _treed.trainSet._EntropyOfClassX.Entropy(data); for (var i = 0; i < attributes.Count; i++) { attributes[i].InformationGain = _treed._TrainSetX.GetGainRatioForCol(data, i, tableEntropy); if (attributes[i].InformationGain > highestInformationGain) { highestInformationGain = attributes[i].InformationGain; highestInformationGainIndex = i; } } /// todo : gainRatio might be all nils /// if (highestInformationGain == 0) { return(__GetRootNodeFroClass_tblAssumeDwelt(data, inEdge)); } return(new TreeNode(attributes[highestInformationGainIndex].Name, highestInformationGainIndex, attributes[highestInformationGainIndex], inEdge)); }
static void Main() { //MyClass my = new MyClass(); //MyClass.Method(); Type type = typeof(MyClass); MyAttribute[] my = type.GetCustomAttributes <MyAttribute>().ToArray(); object[] attributes = null; MyAttribute attribute = null; // Анализ атрибутов типа. // Получаем все аттрибуты заданного типа MyAttribute (false - без проверки базовых классов). attributes = type.GetCustomAttributes(false); foreach (object attributeType in attributes) { attribute = attributeType as MyAttribute; Console.WriteLine("Анализ типа : Number = {0}, Date = {1}", attribute.Number, attribute.Date); } MyAttribute aaa = type.GetCustomAttribute <MyAttribute>(); // Анализ атрибутов метода. // Получаем public static метод - Method. MethodInfo method = type.GetMethod("Method", BindingFlags.Public | BindingFlags.Static); // Получаем все аттрибуты заданного типа MyAttribute (false - без проверки базовых классов). attributes = method.GetCustomAttributes(typeof(MyAttribute), false); foreach (MyAttribute attrib in attributes) { Console.WriteLine("Анализ метода: Number = {0}, Date = {1}", attrib.Number, attrib.Date); } // Delay. Console.ReadKey(); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("Attribute.GetHashCode()"); try { MyAttribute myAttr = new MyAttribute(); myAttr.GetHashCode(); } catch (FieldAccessException e) { TestLibrary.TestFramework.LogError("001", "DDB 125472 is present. Exception:"+e); retVal = false; } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Get the Attribute Hash Code"); try { int intVal = TestLibrary.Generator.GetInt32(-55); MyAttribute myAttr = new MyAttribute(intVal); int hashcode = myAttr.GetHashCode(); if (hashcode != intVal) { TestLibrary.TestFramework.LogError("001", "the ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public void GetAttributesReturnsOnlyOne() { bool inherit = false; MyAttribute attrib = new MyAttribute(); object[] attribs = new object[] { attrib }; MockAttributeProvider provider = new MockAttributeProvider(attribs, inherit); MyAttribute[] result = ReflectionHelper.GetAttributes<MyAttribute>(provider, inherit); Assert.AreEqual<int>(attribs.Length, result.Length); }