Search Results

Search found 1787 results on 72 pages for 'reflection emit'.

Page 7/72 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Extension method using Reflection to Sort

    - by Xavier
    I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well). Here is a sample of implementation: //test function function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) { //Sort entitiesA , based on ClassA MySort method var aSorted = entitiesA.MyExtensionSortMethod(); //Sort entitiesB , based on ClassB MySort method var bSorted = entitiesB.MyExtensionSortMethod(); } //Class A definition public classA: IMySort<classA> { .... public IEnumerable<classA> MySort(IEnumerable<classA> entities) { return entities.OrderBy( ... ).ThenBy( ...); } } public classB: IMySort<classB> { .... public IEnumerable<classB> MySort(IEnumerable<classB> entities) { return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... ); } } //extension method public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new() { //the extension should call MySort of T Type t = typeof(T); var methodInfo = t.GetMethod("MySort"); //invoke MySort var result = methodInfo.Invoke(new T(), new object[] {e}); //Return return (IEnumerable < T >)result; } public interface IMySort<TEntity> where TEntity : class { IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities); } However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?

    Read the article

  • Casting Error with Reflection

    - by Mitchel Sellers
    I have an application that uses plugins that are managed via an interface I then dynamically load the plugin classes and cast them to the interface to work with them. I have the following line of code, assume that IPlugin is my interface. IPlugin _plugin = (IPlugin)Activator.CreateInstance(oInfo.Assembly, oInfo.FullyQualifiedName) This should be pretty simple, create the instance and cast it to the interface. I know that the assembly and fully qualified name values are correct, but I am getting the following exception. Exception= System.InvalidCastException: Unable to cast object of type ‘System.Runtime.Remoting.ObjectHandle’ to type ‘MyNamespace.Components.Integration.IPlugin’. at MyNamespace.Components.Integration.PluginProxy..ctor(Int32 instanceId) Any ideas what could cause this?

    Read the article

  • System.Security.Permissions.SecurityPermission and Reflection on Godaddy

    - by David Murdoch
    I have the following method: public static UserControl LoadControl(string UserControlPath, params object[] constructorParameters) { var p = new Page(); var ctl = p.LoadControl(UserControlPath) as UserControl; // Find the relevant constructor if (ctl != null) { ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constructorParameters.Select(constParam => constParam == null ? "".GetType() : constParam.GetType()).ToArray()); //And then call the relevant constructor if (constructor == null) { throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString()); } constructor.Invoke(ctl, constructorParameters); } // Finally return the fully initialized UC return ctl; } Which when executed on a Godaddy shared host gives me System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

    Read the article

  • access exception when invoking method of an anonymous class using java reflection

    - by Asaf David
    Hello I'm trying to use an event dispatcher to allow a model to notify subscribed listeners when it changes. the event dispatcher receives a handler class and a method name to call during dispatch. the presenter subscribes to the model changes and provide a Handler implementation to be called on changes. Here's the code (I'm sorry it's a bit long). EventDispacther: package utils; public class EventDispatcher<T> { List<T> listeners; private String methodName; public EventDispatcher(String methodName) { listeners = new ArrayList<T>(); this.methodName = methodName; } public void add(T listener) { listeners.add(listener); } public void dispatch() { for (T listener : listeners) { try { Method method = listener.getClass().getMethod(methodName); method.invoke(listener); } catch (Exception e) { System.out.println(e.getMessage()); } } } } Model: package model; public class Model { private EventDispatcher<ModelChangedHandler> dispatcher; public Model() { dispatcher = new EventDispatcher<ModelChangedHandler>("modelChanged"); } public void whenModelChange(ModelChangedHandler handler) { dispatcher.add(handler); } public void change() { dispatcher.dispatch(); } } ModelChangedHandler: package model; public interface ModelChangedHandler { void modelChanged(); } Presenter: package presenter; public class Presenter { private final Model model; public Presenter(Model model) { this.model = model; this.model.whenModelChange(new ModelChangedHandler() { @Override public void modelChanged() { System.out.println("model changed"); } }); } } Main: package main; public class Main { public static void main(String[] args) { Model model = new Model(); Presenter presenter = new Presenter(model); model.change(); } } Now, I except to get the "model changed" message. However, I'm getting an java.lang.IllegalAccessException: Class utils.EventDispatcher can not access a member of class presenter.Presenter$1 with modifiers "public". I understand that the class to blame is the anonymous class i created inside the presenter, however I don't know how to make it any more 'public' than it currently is. If i replace it with a named nested class it seem to work. It also works if the Presenter and the EventDispatcher are in the same package, but I can't allow that (several presenters in different packages should use the EventDispatcher) any ideas?

    Read the article

  • BindingList<T> and reflection!

    - by Aren B
    Background Working in .NET 2.0 Here, reflecting lists in general. I was originally using t.IsAssignableFrom(typeof(IEnumerable)) to detect if a Property I was traversing supported the IEnumerable Interface. (And thus I could cast the object to it safely) However this code was not evaluating to True when the object is a BindingList<T>. Next I tried to use t.IsSubclassOf(typeof(IEnumerable)) and didn't have any luck either. Code /// <summary> /// Reflects an enumerable (not a list, bad name should be fixed later maybe?) /// </summary> /// <param name="o">The Object the property resides on.</param> /// <param name="p">The Property We're reflecting on</param> /// <param name="rla">The Attribute tagged to this property</param> public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla) { Type t = p.PropertyType; //if (t.IsAssignableFrom(typeof(IEnumerable))) if (t.IsSubclassOf(typeof(IEnumerable))) { IEnumerable e = p.GetValue(o, null) as IEnumerable; int count = 0; if (e != null) { foreach (object lo in e) { if (count >= rla.MaxRows) break; ReflectObject(lo, count); count++; } } } } The Intent I want to basically tag lists i want to reflect through with the ReflectedListAttribute and call this function on the properties that has it. (Already Working) Once inside this function, given the object the property resides on, and the PropertyInfo related, get the value of the property, cast it to an IEnumerable (assuming it's possible) and then iterate through each child and call ReflectObject(...) on the child with the count variable.

    Read the article

  • Loading remote assembly from the webservice with reflection

    - by Myat Htut
    I am using Assembly.LoadFrom within a web service to load assemblies from a web site. but the problem is it is in the virutal directory and the server.mappath parses the url like \share\mydll.dll and loadform method failed. Is there anyway to reference dll from the remote location? I've tried passing the url (http:\localhost\downloadable\mydll.dll) and again it got "Could not load file or assembly 'http:\localhost\downloadable\mydll.dll' or one of its dependencies. HTTP download of assemblies has been disabled for this appdomain. (Exception from HRESULT: 0x80131048)"

    Read the article

  • C# reflection, cloning

    - by Enriquev
    Say I have this class Myclass that contains this method: public class MyClass { public int MyProperty { get; set; } public int MySecondProperty { get; set; } public MyOtherClass subClass { get; set; } public object clone<T>(object original, T emptyObj) { FieldInfo[] fis = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); object tempMyClass = Activator.CreateInstance(typeof(T)); foreach (FieldInfo fi in fis) { if (fi.FieldType.Namespace != original.GetType().Namespace) fi.SetValue(tempMyClass, fi.GetValue(original)); else fi.SetValue(tempMyClass, this.clone(fi.GetValue(original), fi.GetValue(original))); } return tempMyClass; } } Then this class: public class MyOtherClass { public int MyProperty777 { get; set; } } when I do this: MyClass a = new MyClass { MyProperty = 1, MySecondProperty = 2, subClass = new MyOtherClass() { MyProperty777 = -1 } }; MyClass b = a.clone(a, a) as MyClass; how come on the second call to clone, T is of type object and not of type MyOtherClass

    Read the article

  • Java Reflection, java.lang.IllegalAccessException Error

    - by rubby
    Hi all, My goal is : Third class will read the name of the class as String from console.Upon reading the name of the class, it will automatically and dynamically (!) generate that class and call its writeout method. If that class is not read from input, it will not be initialized. And I am taking java.lang.IllegalAccessException: Class deneme.class3 can not access a member of class java.lang.Object with modifiers "protected" error. And i don't know how i can fix it.. Can anyone help me? import java.io.*; import java.lang.reflect.*; class class3 { public void run() { try { BufferedReader reader= new BufferedReader(new InputStreamReader(System.in)); String line=reader.readLine(); Class c1 = Class.forName("java.lang.String"); Object obj = new Object(); Class c2 = obj.getClass(); Method writeout = null; for( Method mth : c2.getDeclaredMethods() ) { writeout = mth; break; } Object o = c2.newInstance(); writeout.invoke( o ); } catch(Exception ee) { System.out.println("ERROR! "+ee); } } public void writeout3() { System.out.println("class3"); } } class class4 { public void writeout4() { System.out.println("class4"); } } class ornek { public static void main(String[] args) { System.out.println("Please Enter Name of Class : "); class3 example = new class3(); example.run(); } }

    Read the article

  • C# reflection instantiation

    - by NickLarsen
    I am currently trying to create a generic instance factory for which takes an interface as the generic parameter (enforced in the constructor) and then lets you get instantiated objects which implement that interface from all types in all loaded assemblies. The current implementation is as follows:     public class InstantiationFactory     {         protected Type Type { get; set; }         public InstantiationFactory()         {             this.Type = typeof(T);             if (!this.Type.IsInterface)             {                 // is there a more descriptive exception to throw?                 throw new ArgumentException(/* Crafty message */);             }         }         public IEnumerable GetLoadedTypes()         {             // this line of code found in other stack overflow questions             var types = AppDomain.CurrentDomain.GetAssemblies()                 .SelectMany(a = a.GetTypes())                 .Where(/* lambda to identify instantiable types which implement this interface */);             return types;         }         public IEnumerable GetImplementations(IEnumerable types)         {             var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */                 .Select(x = CreateInstance(x));             return implementations;         }         public IEnumerable GetLoadedImplementations()         {             var loadedTypes = GetLoadedTypes();             var implementations = GetImplementations(loadedTypes);             return implementations;         }         private T CreateInstance(Type type)         {             T instance = default(T);             var constructor = type.GetConstructor(Type.EmptyTypes);             if (/* valid to instantiate test */)             {                 object constructed = constructor.Invoke(null);                 instance = (T)constructed;             }             return instance;         }     } It seems useful to me to have my CreateInstance(Type) function implemented as an extension method so I can reuse it later and simplify the code of my factory, but I can't figure out how to return a strongly typed value from that extension method. I realize I could just return an object:     public static class TypeExtensions     {         public object CreateInstance(this Type type)         {             var constructor = type.GetConstructor(Type.EmptyTypes);             return /* valid to instantiate test */ ? constructor.Invoke(null) : null;         }     } Is it possible to have an extension method create a signature per instance of the type it extends? My perfect code would be this, which avoids having to cast the result of the call to CreateInstance():     Type type = typeof(MyParameterlessConstructorImplementingType);     MyParameterlessConstructorImplementingType usable = type.CreateInstance();

    Read the article

  • Subscribing to a ObservableCollection via reflection

    - by Julian Lettner
    How can I subscribe to a ObservableCollection<??> without knowing the element type of the collection? Is there a way to do this without too many 'magic strings'? This is a question for the .NET version 3.5. I think 4.0 would make my life much easier, right? Type type = collection.GetType(); if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObservableCollection<>)) { // I cannot cast the collection here ObservableCollection<object> x = collection; } Thanks for your time.

    Read the article

  • Execute method with Action<T> argument using Reflection

    - by JGr
    How can i create a Action method to use as a argument to the following function? public void When(Action<T> action) { if (internalValue != null) action(internalValue); } I have the MethodInfo on the method, and the parameter type like so: var methods = value.GetType().GetMethods(); MethodInfo mInfo = methods.First(method => method.Name == "When"); Type parameterType = (mInfo.GetParameters()[0]).ParameterType; But after that i have no idea how to make the actual Action method to pass as argument, i also do not know how to define the Action method body.

    Read the article

  • c# Reflection - Find the Generic Type of a Collection

    - by Andy Clarke
    Hi, I'm reflecting a property 'Blah' its Type is ICollection public ICollection<string> Blah { get; set; } private void button1_Click(object sender, RoutedEventArgs e) { var pi = GetType().GetProperty("Blah"); MessageBox.Show(pi.PropertyType.ToString()); } This gives me (as you'd expect!) ICollection<string> ... But really I want to get the collection type i.e. ICollection (rather than ICollection<string>) - does anyone know how i'd do this please?

    Read the article

  • C# Reflection and Getting Properties

    - by Nathan
    I have the following dummy class structure and I am trying to find out how to get the properties from each instance of the class People in PeopleList. I know how to get the properties from a single instance of People but can't for the life of me figure out how to get it from PeopleList. I am sure this is really straightforward but can someone point me in the right direction? public class Example { public class People { private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { _age = value; } } public People() { } public People(string name, int age) { this._name = name; this._age = age; } } public class PeopleList : List<People> { public static void DoStuff() { PeopleList newList = new PeopleList(); // Do some stuff newList.Add(new People("Tim", 35)); } } }

    Read the article

  • Comparing Object properties using reflection

    - by Kumar
    I have two classes Address and Employee as follows: public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } public class Employee { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public Address EmployeeAddress { get; set; } } I have two employee instances as follows: var emp1Address = new Address(); emp1Address.AddressLine1 = "Microsoft Corporation"; emp1Address.AddressLine2 = "One Microsoft Way"; emp1Address.City = "Redmond"; emp1Address.State = "WA"; emp1Address.Zip = "98052-6399"; var emp1 = new Employee(); emp1.FirstName = "Bill"; emp1.LastName = "Gates"; emp1.EmployeeAddress = emp1Address; var emp2Address = new Address(); emp2Address.AddressLine1 = "Gates Foundation"; emp2Address.AddressLine2 = "One Microsoft Way"; emp2Address.City = "Redmond"; emp2Address.State = "WA"; emp2Address.Zip = "98052-6399"; var emp2 = new Employee(); emp2.FirstName = "Melinda"; emp2.LastName = "Gates"; emp2.EmployeeAddress = emp2Address; Now how can I write a method which compares these two employees and returns the list of properties which have different values. So in this example I would like the result to be FirstName and Address.AddressLine1 .

    Read the article

  • Reflection & Parameters in C#

    - by Jim
    Hello, I'm writing an application that runs "things" to a schedule. Idea being that the database contains assembly, method information and also the parameter values. The timer will come along, reflect the method to be run, add the parameters and then execute the method. Everything is fine except for the parameters. So, lets say the method accepts an ENUM of CustomerType where CustomerType has two values of CustomerType.Master and CustomerType.Associate. EDIT I don't the type of parameter that will be getting passed in. ENUM used as an example END OF EDIT We want to run Method "X" and pass in parameter "CustomerType.Master". In the database, there will be a varchar entry of "CustomerType.Master". How do I convert the string "CustomerType.Master" into a type of CustomerType with a value of "Master" generically? Thanks in advance, Jim

    Read the article

  • Getting fields of a class through reflection

    - by Water Cooler v2
    I've done it a gazillion times in the past and successfully so. This time, I'm suffering from lapses of amnesia. So, I am just trying to get the fields on an object. It is an embarrassingly simple and stupid piece of code that I am writing in a test solution before I do something really useful in production code. Strangely, the GetFieldsOf method reports a zero length array on the "Amazing" class. Help. class Amazing { private NameValueCollection _nvc; protected NameValueCollection _myDict; } private static FieldInfo[] GetFieldsOf(string className, string nameSpace = "SomeReflection") { Type t; return (t = Assembly.GetExecutingAssembly().GetType( string.Format("{0}.{1}", nameSpace, className) )) == null ? null : t.GetFields(); }

    Read the article

  • Generics and reflection in Java

    - by Ragesh
    This is probably a very basic question, but I'm really new to generics in Java and I'm having a hard time altering my thought process from the way things are done in C#, so bear with me. I'm trying to build a generic repository in Java. I've created an IRepository interface that looks like this: public interface IRepository<T extends IEntity> And a Repository class that looks like this: public class Repository<T extends IEntity> implements IRepository<T> Now, from within the constructor of my Repository class, I'd like to be able to "divine" the exact type of T. For example, if I instantiated a repository like this: IRepository<MyClass> repo = new Repository<MyClass>(); I'd like to know that T is actually MyClass. This is trivial in C#, but obviously generics are a totally different beast in Java and I can't seem to find anything that would help me do this.

    Read the article

  • Reflection and Generics get value of property

    - by GigaPr
    Hi i am trying to implement a generic method which allows to output csv file public static void WriteToCsv<T>(List<T> list) where T : new() { const string attachment = "attachment; filename=PersonList.csv"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.AddHeader("content-disposition", attachment); HttpContext.Current.Response.ContentType = "text/csv"; HttpContext.Current.Response.AddHeader("Pragma", "public"); bool isFirstRow = true; foreach (T item in list) { //Get public properties PropertyInfo[] propertyInfo = item.GetType().GetProperties(); while (isFirstRow) { WriteColumnName(propertyInfo); isFirstRow = false; } Type type = typeof (T); StringBuilder stringBuilder = new StringBuilder(); foreach (PropertyInfo info in propertyInfo) { //string value ???? I am trying to get the value of the property info for the item object } HttpContext.Current.Response.Write(stringBuilder.ToString()); HttpContext.Current.Response.Write(Environment.NewLine); } HttpContext.Current.Response.End(); } but I am not able to get the value of the object's property Any suggestion? Thanks

    Read the article

  • [.Net/Reflection] Getting the .Net corresponding type of a C# type

    - by Serious
    Hello, is there a function that, given a C# type's string representation, returns the corresponding .Net type or .Net type's string representation; or any way to achieve this. For example : "bool" - System.Boolean or "System.Boolean" "int" - System.Int32 or "System.Int32" ... Thanks. Edit : really sorry, it's not a "type to type" mapping that I wish but either a "string to string" mapping or a "string to type" mapping.

    Read the article

  • java reflection

    - by user622222
    Hi all, System.out.println("Class name : "); BufferedReader reader= new BufferedReader(new InputStreamReader(System.in)); String line = reader.readLine(); Class<?> writeoutClass = Class.forName(line); Method Writeout = null; for (Method mth : writeoutClass.getDeclaredMethods()) { if (mth.getName().startsWith("Writeout")) { Writeout = mth; break; } It's giving error like that; java.lang.ClassNotFoundException: a How can i generate that class?

    Read the article

  • How to dynamically use the PropertyType reflection attribute to create a respective typed Function<

    - by vsj
    I want to use type returned by PropertyType to create a typed function. I found this similiar http://stackoverflow.com/questions/914578/using-type-returned-by-type-gettype-in-c but this mentions how to create a list but does not mention how we can create a Func<. Please help me out. Pseudocode: PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName"); Type T=inf.PropertyType; Expression<Func<SomeClass,T>> le = GetPropertyOrFieldByName<SomeClass, T>("PropertyName");

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >