Search Results

Search found 1575 results on 63 pages for 'reflection'.

Page 10/63 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • What are the use cases for this static reflection code?

    - by Maslow
    This is Oliver Hanappi's static reflection code he posted on stackoverflow private static string GetMemberName(Expression expression) { switch (expression.NodeType) { case ExpressionType.MemberAccess: var memberExpression = (MemberExpression)expression; var supername = GetMemberName(memberExpression.Expression); if (String.IsNullOrEmpty(supername)) return memberExpression.Member.Name; return String.Concat(supername, '.', memberExpression.Member.Name); case ExpressionType.Call: var callExpression = (MethodCallExpression)expression; return callExpression.Method.Name; case ExpressionType.Convert: var unaryExpression = (UnaryExpression)expression; return GetMemberName(unaryExpression.Operand); case ExpressionType.Parameter: return String.Empty; default: throw new ArgumentException("The expression is not a member access or method call expression"); } } I have the public wrapper methods: public static string Name<T>(Expression<Action<T>> expression) { return GetMemberName(expression.Body); } public static string Name<T>(Expression<Func<T, object>> expression) { return GetMemberName(expression.Body); } then added my own method shortcuts public static string ClassMemberName<T>(this T sourceType,Expression<Func<T,object>> expression) { return GetMemberName(expression.Body); } public static string TMemberName<T>(this IEnumerable<T> sourceList, Expression<Func<T,object>> expression) { return GetMemberName(expression.Body); } What are examples of code that would necessitate or take advantage of the different branches in the GetMemberName(Expression expression) switch? what all is this code capable of making strongly typed?

    Read the article

  • Associate "Code/Properties/Stuff" with Fields in C# without reflection. I am too indoctrinated by J

    - by AlexH
    I am building a library to automatically create forms for Objects in the project that I am working on. The codebase is in C#, and essentially we have a HUGE number of different objects to store information about different things. If I send these objects to the client side as JSON, it is easy enough to programatically inspect them to generate a form for all of the properties. The problem is that I want to be able to create a simple way of enforcing permissions and doing validation on the client side. It needs to be done on a field by field level. In javascript I would do this by creating a parallel object structure, which had some sort of { permissions : "someLevel", validator : someFunction } object at the nodes. With empty nodes implying free permissions and universal validation. This would let me simply iterate over the new object and the permissions object, run the check, and deal with the result. Because I am overfamilar with the hammer that is javascript, this is really the only way that I can see to deal with this problem. My first implementation thus uses reflection to let me treat objects as dictionaries, that can be programatically iterated over, and then I just have dictionaries of dictionaries of PermissionRule objects which can be compared with. Very javascripty. Very awkward. Is there some better way that I can do this? Essentially a way to associate a data set with each property, and then iterate over those properties. Or else am I Doing It Wrong?

    Read the article

  • Java reflection Method invocations yield result faster than Fields?

    - by omerkudat
    I was microbenchmarking some code (please be nice) and came across this puzzle: when reading a field using reflection, invoking the getter Method is faster than reading the Field. Simple test class: private static final class Foo { public Foo(double val) { this.val = val; } public double getVal() { return val; } public final double val; // only public for demo purposes } We have two reflections: Method m = Foo.class.getDeclaredMethod("getVal", null); Field f = Foo.class.getDeclaredField("val"); Now I call the two reflections in a loop, invoke on the Method, and get on the Field. A first run is done to warm up the VM, a second run is done with 10M iterations. The Method invocation is consistently 30% faster, but why? Note that getDeclaredMethod and getDeclaredField are not called in the loop. They are called once and executed on the same object in the loop. I also tried some minor variations: made the field non-final, transitive, non-public, etc. All of these combinations resulted in statistically similar performance. Edit: This is on WinXP, Intel Core2 Duo, Sun JavaSE build 1.6.0_16-b01, running under jUnit4 and Eclipse.

    Read the article

  • Getting the constructor of an Interface Type through reflection?

    - by Will Marcouiller
    I have written a generic type: IDirectorySource<T> where T : IDirectoryEntry, which I'm using to manage Active Directory entries through my interfaces objects: IGroup, IOrganizationalUnit, IUser. So that I can write the following: IDirectorySource<IGroup> groups = new DirectorySource<IGroup>(); // Where IGroup implements `IDirectoryEntry`, of course.` foreach (IGroup g in groups.ToList()) { listView1.Items.Add(g.Name).SubItems.Add(g.Description); } From the IDirectorySource<T>.ToList() methods, I use reflection to find out the appropriate constructor for the type parameter T. However, since T is given an interface type, it cannot find any constructor at all! Of course, I have an internal class Group : IGroup which implements the IGroup interface. No matter how hard I have tried, I can't figure out how to get the constructor out of my interface through my implementing class. [DirectorySchemaAttribute("group")] public interface IGroup { } internal class Group : IGroup { internal Group(DirectoryEntry entry) { NativeEntry = entry; Domain = NativeEntry.Path; } // Implementing IGroup interface... } Within the ToList() method of my IDirectorySource<T> interface implementation, I look for the constructor of T as follows: internal class DirectorySource<T> : IDirectorySource<T> { // Implementing properties... // Methods implementations... public IList<T> ToList() { Type t = typeof(T) // Let's assume we're always working with the IGroup interface as T here to keep it simple. // So, my `DirectorySchema` property is already set to "group". // My `DirectorySearcher` is already instantiated here, as I do it within the DirectorySource<T> constructor. Searcher.Filter = string.Format("(&(objectClass={0}))", DirectorySchema) ConstructorInfo ctor = null; ParameterInfo[] params = null; // This is where I get stuck for now... Please see the helper method. GetConstructor(out ctor, out params, new Type() { DirectoryEntry }); SearchResultCollection results = null; try { results = Searcher.FindAll(); } catch (DirectoryServicesCOMException ex) { // Handling exception here... } foreach (SearchResult entry in results) entities.Add(ctor.Invoke(new object() { entry.GetDirectoryEntry() })); return entities; } } private void GetConstructor(out ConstructorInfo constructor, out ParameterInfo[] parameters, Type paramsTypes) { Type t = typeof(T); ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); bool found = true; foreach (ContructorInfo c in ctors) { parameters = c.GetParameters(); if (parameters.GetLength(0) == paramsTypes.GetLength(0)) { for (int index = 0; index < parameters.GetLength(0); ++index) { if (!(parameters[index].GetType() is paramsTypes[index].GetType())) found = false; } if (found) { constructor = c; return; } } } // Processing constructor not found message here... } My problem is that T will always be an interface, so it never finds a constructor. Might somebody guide me to the right path to follow in this situation?

    Read the article

  • How to create contracts in python

    - by recluze
    I am just moving to python from Java and have a question about the way the two do things. My question relates to contracts. An example: an application defines an interface that all plugins must implement and then the main application can call it. In Java: public interface IPlugin { public Image modify(Image img); } public class MainApp { public main_app_logic() { String pluginName = "com.example.myplugin"; IPlugin x = (IPlugin) Class.forName(pluginName); x.modify(someimg); } } The plugin implements the interface and we use reflection in main app to call it. That way, there's a contract between the main app and the plugin that both can refer to. How does one go about doing something similar in Python? And also, which approach is better? p.s. I'm not posting this on SO because I'm much more concerned with the philosophy behind the two approaches.

    Read the article

  • Understanding how texCUBE works and writing cubemaps properly into a cube rendertarget

    - by cubrman
    My goal is to create accurate reflections, sampled from a dynamic cubemap, for specific 3d objects (mostly lights) in XNA 4.0. To sample the cubemap I compute the 3d reflection vector in a classic way: half3 ReflectionVec = reflect(-directionToCamera, Normal.rgb); I then use the vector to get the actual reflected color: half3 ReflectionCol = texCUBElod(ReflectionSampler, float4(ReflectionVec, 0)); The cubemap I am sampling from is a RenderTarget with 6 flat faces. So my question is, given the 3d world position of an arbitrary 3d object, how can I make sure that I get accurate reflections of this object, when I re-render the cubemap. Should I build the ViewProjection matrix in a specific way? Or is there any other approach?

    Read the article

  • HLSL How to flip geometry horizontally

    - by cubrman
    I want to flip my asymmetric 3d model horizontally in the vertex shader alongside an arbitrary plane parallel to the YZ plane. This should switch everything for the model from the left hand side to the right hand side (like flipping it in Photoshop). Doing it in pixel shader would be a huge computational cost (extra RT, more fullscreen samples...), so it must be done in the vertex shader. Once more: this is NOT reflection, i need to flip THE WHOLE MODEL. I thought I could simply do the following: Turn off culling. Run the following code in the vertex shader: input.Position = mul(input.Position, World); // World[3][0] holds x value of the model's pivot in the World. if (input.Position.x <= World[3][0]) input.Position.x += World[3][0] - input.Position.x; else input.Position.x -= input.Position.x - World[3][0]; ... The model is never drawn. Where am I wrong? I presume that messes up the index buffer. Can something be done about it? P.S. it's INSANELY HARD to format code here. Thanks to Panda I found my problem. SOLUTION: // Do thins before anything else in the vertex shader. Position.x *= -1; // To invert alongside the object's YZ plane.

    Read the article

  • Input/Output console window in XNA

    - by Will Bagley
    I am currently making a simple game in XNA but am at a point where testing various aspect gets a bit tricky, especially when you have to wait till you have 1000 score to see if your animation is playing correctly etc. Of course i could just edit the starting variable in the code before I launched but I have recently been interested in trying to implement a console style window which can print out values and take input to alter public variables during run-time. I am aware that VS has the immediate window which achieves a similar thing but i would prefer mine is an actual part of the game with the intention that the user may have limited access to it in the future. Some of the key things i have yet to find an answer to after looking around for a while are: how i would support free text entry how i would access variables during runtime how i would edit these variable I have also read about using a property grid from windows form aps (and partially reflection) which looked like it could simplify a lot of things but i am not sure how I would get that running inside my XNA game window or how i would get it to not look out of place (as the visual aspect of is seems to be aimed just for development time viewing). All in all I'm quite open to any suggestions on how to approach this task as currently I'm not sure where to start. Thanks in advance.

    Read the article

  • .Net reflection to get description of class / property etc?

    - by ClarkeyBoy
    Hi, I know its unlikely but I was wondering if there is any way to get the comments (i.e. the bits after the ''') of a class or property..? I have managed to get a list of properties of a class using the PropertyInfo class but I cant find a way to get the comments / description.. I need it for a guide I am writing for the administrators of my site - it would be great if it could automatically update if new properties are added, so there is no need to worry about updating it in the future too much. Anyone know how to do this? Thanks in advance. Regards, Richard

    Read the article

  • Using reflection to change static final File.separatorChar for unit testing?

    - by Stefan Kendall
    Specifically, I'm trying to create a unit test for a method which requires uses File.separatorChar to build paths on windows and unix. The code must run on both platforms, and yet I get errors with JUnit when I attempt to change this static final field. Anyone have any idea what's going on? Field field = java.io.File.class.getDeclaredField( "separatorChar" ); field.setAccessible(true); field.setChar(java.io.File.class,'/'); When I do this, I get IllegalAccessException: Can not set static final char field java.io.File.separatorChar to java.lang.Character Thoughts?

    Read the article

  • .Net reflection to get developers comments about class / property etc?

    - by ClarkeyBoy
    Hi, I know its unlikely but I was wondering if there is any way to get the comments (i.e. the bits after the ''') of a class or property..? I have managed to get a list of properties of a class using the PropertyInfo class but I cant find a way to get the comments / description.. I need it for a guide I am writing for the administrators of my site - it would be great if it could automatically update if new properties are added, so there is no need to worry about updating it in the future too much. Anyone know how to do this? Thanks in advance. Regards, Richard

    Read the article

  • How to get MinValue/MaxValue of a certain ValueType via reflection?

    - by marco.ragogna
    I need to this at runtime. I checked using Reflector and value types line like Int16, for example, should contain <Serializable, StructLayout(LayoutKind.Sequential), ComVisible(True)> _ Public Structure Int16 Implements IComparable, IFormattable, IConvertible, IComparable(Of Short), IEquatable(Of Short) Public Const MaxValue As Short = &H7FFF Public Const MinValue As Short = -32768 End Structure But the following code is not working Dim dummyValue = Activator.CreateInstance(GetType(UInt16)) Dim minValue As IComparable = DirectCast(dummyValue.GetType.GetProperty("MinValue").GetValue(dummyValue, Nothing), IComparable) any idea how to solve?

    Read the article

  • How to use reflection to call a method and pass parameters whose types are unknown at compile time?

    - by MandoMando
    I'd like to call methods of a class dynamically with parameter values that are "parsed" from a string input. For example: I'd like to call the following program with these commands: c:myprog.exe MethodA System.Int32 777 c:myprog.exe MethodA System.float 23.17 c:myprog.exe MethodB System.Int32& 777 c:myprog.exe MethodC System.Int32 777 System.String ThisCanBeDone static void Main(string[] args) { ClassA aa = new ClassA(); System.Type[] types = new Type[args.Length / 2]; object[] ParamArray = new object[types.Length]; for (int i=0; i < types.Length; i++) { types[i] = System.Type.GetType(args[i*2 + 1]); // LINE_X: this will obviously cause runtime error invalid type/casting ParamArray[i] = args[i*2 + 2]; MethodInfo callInfo = aa.GetType().GetMethod(args[0],types); callInfo.Invoke(aa, ParamArray); } // In a non-changeable classlib: public class ClassA { public void MethodA(int i) { Console.Write(i.ToString()); } public void MethodA(float f) { Console.Write(f.ToString()); } public void MethodB(ref int i) { Console.Write(i.ToString()); i++; } public void MethodC(int i, string s) { Console.Write(s + i.ToString()); } public void MethodA(object o) { Console.Write("Argg! Type Trapped!"); } } "LINE_X" in the above code is the sticky part. For one, I have no idea how to assign value to a int or a ref int parameter even after I create it using Activator.CreatInstance or something else. The typeConverter does come to mind, but then that requires an explicit compile type casting as well. Am I looking at CLR with JavaScript glasses or there is way to do this?

    Read the article

  • How to use reflection to get a default constructor?

    - by Qwertie
    I am writing a library that generates derived classes of abstract classes dynamically at runtime. The constructor of the derived class needs a MethodInfo of the base class constructor so that it can invoke it. However, for some reason Type.GetConstructor() returns null. For example: abstract class Test { public abstract void F(); } public static void Main(string[] args) { ConstructorInfo constructor = typeof(Test).GetConstructor( BindingFlags.NonPublic | BindingFlags.Public, null, System.Type.EmptyTypes, null); // returns null! } Note that GetConstructor returns null even if I explicitly declare a constructor in Test, and even if Test is not abstract.

    Read the article

  • Reflection PropertyInfo GetValue call errors out for Collection<> type property.

    - by Vinit Sankhe
    Hey Guys, I have a propertyInfo object and I try to do a GetValue using it. object source = mysourceObject //This object has a property "Prop1" of type Collection<>. var propInfo = source.GetType().GetProperty("Prop1"); var propValue = prop.GetValue(this, null); // do whatever with propValue // ... I get error at the GetValue() call as "Value cannot be null.\r\nParameter name: source" "Prop1" is a plain property declared as Collection. prop.PropertyType = {Name = "Collection1" FullName = "System.Collections.ObjectModel.Collection1[[Application1.DummyClass, Application1, Version=1.5.5.5834, Culture=neutral, PublicKeyToken=628b2ce865838339]]"} System.Type {System.RuntimeType}

    Read the article

  • c# reflection: How can I invoke a method with an out parameter ?

    - by ldp615
    I want expose WebClient.DownloadDataInternal method like below: [ComVisible(true)] public class MyWebClient : WebClient { private MethodInfo _DownloadDataInternal; public MyWebClient() { _DownloadDataInternal = typeof(WebClient).GetMethod("DownloadDataInternal", BindingFlags.NonPublic | BindingFlags.Instance); } public byte[] DownloadDataInternal(Uri address, out WebRequest request) { _DownloadDataInternal.Invoke(this, new object[] { address, out request }); } } WebClient.DownloadDataInternal has a out parameter, I don't know how to invoke it. Help!

    Read the article

  • Java: how to avoid circual references when dumping object information with reflection?

    - by Tom
    I've modified an object dumping method to avoid circual references causing a StackOverflow error. This is what I ended up with: //returns all fields of the given object in a string public static String dumpFields(Object o, int callCount, ArrayList excludeList) { //add this object to the exclude list to avoid circual references in the future if (excludeList == null) excludeList = new ArrayList(); excludeList.add(o); callCount++; StringBuffer tabs = new StringBuffer(); for (int k = 0; k < callCount; k++) { tabs.append("\t"); } StringBuffer buffer = new StringBuffer(); Class oClass = o.getClass(); if (oClass.isArray()) { buffer.append("\n"); buffer.append(tabs.toString()); buffer.append("["); for (int i = 0; i < Array.getLength(o); i++) { if (i < 0) buffer.append(","); Object value = Array.get(o, i); if (value != null) { if (excludeList.contains(value)) { buffer.append("circular reference"); } else if (value.getClass().isPrimitive() || value.getClass() == java.lang.Long.class || value.getClass() == java.lang.String.class || value.getClass() == java.lang.Integer.class || value.getClass() == java.lang.Boolean.class) { buffer.append(value); } else { buffer.append(dumpFields(value, callCount, excludeList)); } } } buffer.append(tabs.toString()); buffer.append("]\n"); } else { buffer.append("\n"); buffer.append(tabs.toString()); buffer.append("{\n"); while (oClass != null) { Field[] fields = oClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i] == null) continue; buffer.append(tabs.toString()); fields[i].setAccessible(true); buffer.append(fields[i].getName()); buffer.append("="); try { Object value = fields[i].get(o); if (value != null) { if (excludeList.contains(value)) { buffer.append("circular reference"); } else if ((value.getClass().isPrimitive()) || (value.getClass() == java.lang.Long.class) || (value.getClass() == java.lang.String.class) || (value.getClass() == java.lang.Integer.class) || (value.getClass() == java.lang.Boolean.class)) { buffer.append(value); } else { buffer.append(dumpFields(value, callCount, excludeList)); } } } catch (IllegalAccessException e) { System.out.println("IllegalAccessException: " + e.getMessage()); } buffer.append("\n"); } oClass = oClass.getSuperclass(); } buffer.append(tabs.toString()); buffer.append("}\n"); } return buffer.toString(); } The method is initially called like this: System.out.println(dumpFields(obj, 0, null); So, basically I added an excludeList which contains all the previousely checked objects. Now, if an object contains another object and that object links back to the original object, it should not follow that object further down the chain. However, my logic seems to have a flaw as I still get stuck in an infinite loop. Does anyone know why this is happening?

    Read the article

  • PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?

    - by flesh
    This (shortened) code.. for (int i = 0; i < count; i++) { object obj = propertyInfo.GetValue(Tcurrent, new object[] { i }); } .. is throwing a 'TargetParameterCountException : Parameter count mismatch' exception. The underlying type of 'propertyInfo' is a Collection of some T. 'count' is the number of items in the collection. I need to iterate through the collection and perform an operation on obj. Advice appreciated.

    Read the article

  • How to get the parameter names of an object's constructors (reflection)?

    - by Tom
    Say I somehow got an object reference from an other class: Object myObj = anObject; Now I can get the class of this object: Class objClass = myObj.getClass(); Now, I can get all constructors of this class: Constructor[] constructors = objClass.getConstructors(); Now, I can loop every constructor: if (constructors.length > 0) { for (int i = 0; i < constructors.length; i++) { System.out.println(constructors[i]); } } This is already giving me a good summary of the constructor, for example a constructor public Test(String paramName) is shown as public Test(java.lang.String) Instead of giving me the class type however, I want to get the name of the parameter.. in this case "paramName". How would I do that? I tried the following without success: if (constructors.length > 0) { for (int iCon = 0; iCon < constructors.length; iCon++) { Class[] params = constructors[iCon].getParameterTypes(); if (params.length > 0) { for (int iPar = 0; iPar < params.length; iPar++) { Field fields[] = params[iPar].getDeclaredFields(); for (int iFields = 0; iFields < fields.length; iFields++) { String fieldName = fields[i].getName(); System.out.println(fieldName); } } } } } Unfortunately, this is not giving me the expected result. Could anyone tell me how I should do this or what I am doing wrong? Thanks!

    Read the article

  • Greatest Hits : A reflection on my 2010 blog posts

    - by AaronBertrand
    Okay, I'm following the lead of Joe Webb ( blog | twitter ), who recently posted " My Most Popular Posts From 2010 ." I think it can be a very useful exercise to back and look at what blog posts were popular and, arguably more importantly, which posts were most thought-provoking and generated the most dialog (whether it is praise, heckling, or a mixture). I think you can a learn a lot about your blogging habits and perhaps where to focus energy in the future/ You can also be quite surprised at which...(read more)

    Read the article

  • F# and the rose-tinted reflection

    - by CliveT
    We're already seeing increasing use of many cores on client desktops. It is a change that has been long predicted. It is not just a change in architecture, but our notions of efficiency in a program. No longer can we focus on the asymptotic complexity of an algorithm by counting the steps that a single core processor would take to execute it. Instead we'll soon be more concerned about the scalability of the algorithm and how well we can increase the performance as we increase the number of cores. This may even lead us to throw away our most efficient algorithms, and switch to less efficient algorithms that scale better. We might even be willing to waste cycles in order to speculatively execute at the algorithm rather than the hardware level. State is the big headache in this parallel world. At the hardware level, main memory doesn't necessarily contain the definitive value corresponding to a particular address. An update to a location might still be held in a CPU's local cache and it might be some time before the value gets propagated. To get the latest value, and the notion of "latest" takes a lot of defining in this world of rapidly mutating state, the CPUs may well need to communicate to decide who has the definitive value of a particular address in order to avoid lost updates. At the user program level, this means programmers will need to lock objects before modifying them, or attempt to avoid the overhead of locking by understanding the memory models at a very deep level. I think it's this need to avoid statefulness that has led to the recent resurgence of interest in functional languages. In the 1980s, functional languages started getting traction when research was carried out into how programs in such languages could be auto-parallelised. Sadly, the impracticality of some of the languages, the overheads of communication during this parallel execution, and rapid improvements in compiler technology on stock hardware meant that the functional languages fell by the wayside. The one thing that these languages were good at was getting rid of implicit state, and this single idea seems like a solution to the problems we are going to face in the coming years. Whether these languages will catch on is hard to predict. The mindset for writing a program in a functional language is really very different from the way that object-oriented problem decomposition happens - one has to focus on the verbs instead of the nouns, which takes some getting used to. There are a number of hybrid functional/object languages that have been becoming more popular in recent times. These half-way houses make it easy to use functional ideas for some parts of the program while still allowing access to the underlying object-focused platform without a great deal of impedance mismatch. One example is F# running on the CLR which, in Visual Studio 2010, has because a first class member of the pack. Inside Visual Studio 2010, the tooling for F# has improved to the point where it is easy to set breakpoints and watch values change while debugging at the source level. In my opinion, it is the tooling support that will enable the widespread adoption of functional languages - without this support, people will put off any transition into the functional world for as long as they possibly can. Without tool support it will make it hard to learn these languages. One tool that doesn't currently support F# is Reflector. The idea of decompiling IL to a functional language is daunting, but F# is potentially so important I couldn't dismiss the idea. As I'm currently developing Reflector 6.5, I thought it wise to take four days just to see how far I could get in doing so, even if it achieved little more than to be clearer on how much was possible, and how long it might take. You can read what happened here, and of the insights it gave us on ways to improve the tool.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >