Search Results

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

Page 18/63 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Populating and Using Dynamic Classes in C#/.NET 4.0

    - by Bob
    In our application we're considering using dynamically generated classes to hold a lot of our data. The reason for doing this is that we have customers with tables that have different structures. So you could have a customer table called "DOG" (just making this up) that contains the columns "DOGID", "DOGNAME", "DOGTYPE", etc. Customer #2 could have the same table "DOG" with the columns "DOGID", "DOG_FIRST_NAME", "DOG_LAST_NAME", "DOG_BREED", and so on. We can't create classes for these at compile time as the customer can change the table schema at any time. At the moment I have code that can generate a "DOG" class at run-time using reflection. What I'm trying to figure out is how to populate this class from a DataTable (or some other .NET mechanism) without extreme performance penalties. We have one table that contains ~20 columns and ~50k rows. Doing a foreach over all of the rows and columns to create the collection take about 1 minute, which is a little too long. Am I trying to come up with a solution that's too complex or am I on the right track? Has anyone else experienced a problem like this? Create dynamic classes was the solution that a developer at Microsoft proposed. If we can just populate this collection and use it efficiently I think it could work.

    Read the article

  • How to limit setAccessible to only "legitimate" uses?

    - by polygenelubricants
    The more I learned about the power of setAccessible, the more astonished I am at what it can do. This is adapted from my answer to the question (Using reflection to change static final File.separatorChar for unit testing). import java.lang.reflect.*; public class EverythingIsTrue { static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static void main(String args[]) throws Exception { setFinalStatic(Boolean.class.getField("FALSE"), true); System.out.format("Everything is %s", false); // "Everything is true" } } You can do truly outrageous stuff: public class UltimateAnswerToEverything { static Integer[] ultimateAnswer() { Integer[] ret = new Integer[256]; java.util.Arrays.fill(ret, 42); return ret; } public static void main(String args[]) throws Exception { EverythingIsTrue.setFinalStatic( Class.forName("java.lang.Integer$IntegerCache") .getDeclaredField("cache"), ultimateAnswer() ); System.out.format("6 * 9 = %d", 6 * 9); // "6 * 9 = 42" } } Presumably the API designers realize how abusable setAccessible can be, but must have conceded that it has legitimate uses to provide it. So my questions are: What are the truly legitimate uses for setAccessible? Could Java has been designed as to NOT have this need in the first place? What would the negative consequences (if any) of such design be? Can you restrict setAccessible to legitimate uses only? Is it only through SecurityManager? How does it work? Whitelist/blacklist, granularity, etc? Is it common to have to configure it in your applications?

    Read the article

  • Stuck trying to get Log4Net to work with Dependency Injection

    - by Pure.Krome
    I've got a simple winform test app i'm using to try some Log4Net Dependency Injection stuff. I've made a simple interface in my Services project :- public interface ILogging { void Debug(string message); // snip the other's. } Then my concrete type will be using Log4Net... public class Log4NetLogging : ILogging { private static ILog Log4Net { get { return LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } public void Debug(string message) { if (Log4Net.IsDebugEnabled) { Log4Net.Debug(message); } } } So far so good. Nothing too hard there. Now, in a different project (and therefore namesapce), I try and use this ... public partial class Form1 : Form { public Form1() { FileInfo fileInfo = new FileInfo("Log4Net.config"); log4net.Config.XmlConfigurator.Configure(fileInfo); } private void Foo() { // This would be handled with DI, but i've not set it up // (on the constructor, in this code example). ILogging logging = new Log4NetLogging(); logging.Debug("Test message"); } } Ok .. also pretty simple. I've hardcoded the ILogging instance but that is usually dependency injected via the constructor. Anyways, when i check this line of code... return LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); the DeclaringType type value is of the Service namespace, not the type of the Form (ie. X.Y.Z.Form1) which actually called the method. Without passing the type INTO method as another argument, is there anyway using reflection to figure out the real method that called it?

    Read the article

  • Java - Calling all methods of a class

    - by Thomas Eschemann
    I'm currently working on an application that has to render several Freemarker templates. So far I have a Generator class that handles the rendering. The class looks more or less like this: public class Generator { public static void generate(…) { renderTemplate1(); renderTemplate2(); renderTemplate3(); } private static void render(…) { // renders the template } private static void renderTemplate1() { // Create config object for the rendering // and calls render(); }; private static void renderTemplate1() { // Create config object for the rendering // and calls render(); }; … } This works, but it doesn't really feel right. What I would like to do is create a class that holds all the renderTemplate...() methods and then call them dynamically from my Generator class. This would make it cleaner and easier to extend. I was thinking about using something like reflection, but it doesn't really feel like a good solution either. Any idea on how to implement this properly ?

    Read the article

  • Statically checking a Java app for link errors

    - by monorailkitty
    I have a scenario where I have code written against version 1 of a library but I want to ship version 2 of the library instead. The code has shipped and is therefore not changeable. I'm concerned that it might try to access classes or members of the library that existed in v1 but have been removed in v2. I figured it would be possible to write a tool to do a simple check to see if the code will link against the newer version of the library. I appreciate that the code may still be very broken even if the code links. I am thinking about this from the other side - if the code won't link then I can be sure there is a problem. As far as I can see, I need to run through the bytecode checking for references, method calls and field accesses to library classes then use reflection to check whether the class/member exists. I have three-fold question: (1) Does such a tool exist already? (2) I have a niggling feeling it is much more complicated that I imagine and that I have missed something major - is that the case? (3) Do you know of a handy library that would allow me to inspect the bytecode such that I can find the method calls, references etc.? Thanks!

    Read the article

  • What are the interets of synthetic methods?

    - by romaintaz
    Problem One friend suggested an interesting problem. Given the following code: public class OuterClass { private String message = "Hello World"; private class InnerClass { private String getMessage() { return message; } } } From an external class, how may I print the message variable content? Of course, changing the accessibility of methods or fields is not allowed. (the source here, but it is a french blog) Solution The code to solve this problem is the following: try { Method m = OuterClass.class.getDeclaredMethod("access$000", OuterClass.class); OuterClass outerClass = new OuterClass(); System.out.println(m.invoke(outerClass, outerClass)); } catch (Exception e) { e.printStackTrace(); } Note that the access$000 method name is not really standard (even if this format is the one that is strongly recommanded), and some JVM will name this method access$0. Thus, a better solution is to check for synthetic methods: Method method = null; int i = 0; while ((method == null) && (i < OuterClass.class.getDeclaredMethods().length)) { if (OuterClass.class.getDeclaredMethods()[i].isSynthetic()) { method = OuterClass.class.getDeclaredMethods()[i]; } i++; } if (method != null) { try { System.out.println(method.invoke(null, new OuterClass())); } catch (Exception e) { e.printStackTrace(); } } So the interesting point in this problem is to highlight the use of synthetic methods. With these methods, I can access a private field as it was done in the solution. Of course, I need to use reflection, and I think that the use of this kind of thing can be quite dangerous... Question What is the interest - for me, as a developer - of a synthetic method? What can be a good situation where using the synthetic can be useful?

    Read the article

  • Complicated API issue with calling assemblies dynamically?

    - by Stefanos Tses
    I have an interesting challenge that I'm wondering if anyone here can give me some direction. I'm writing a .Net windows forms application that runs on a network and uses an SQL Server to save and pull data. I want to offer a mini "plugin" API, where developers can build their own assemblies and implement a specific interface (IDataManipulate). These assemblies then can be used by my application to call the interface functions and do something. I can create assemblies using my API, copy the file to a folder in my local hard drive and configure my application to use Reflection to call a specific function from the implemented interface (IDataManipulate.Execute). The problem: Since the application will be installed in multiple workstations in the network, is impossible to copy the plugin dlls the users will create to each machine. Solutions I tried: Solution 1 Copy the API dll to a network share. Problem: Requires AllowPartiallyTrustedCallersAttribute, which requires .Net singing, which I can't force from my users. Solution 2 (preferred) Serialize the dll object, save it to the database, deserialize it and call IDataManipulate.Execute. Problem: After deserialization, I try cast it to a IDataManipulate object but returns an error looking for the actual dll file. Solution 3 Save the dll bytes as byte[] to the database and recreate the dll at the local PC every time the user starts my application. Problem: Dll may have dependencies, which I don't know if I can detect. Any suggestions will be greatly appreciated. Thanks

    Read the article

  • C#: How to get all public (both get and set) string properties of a type

    - by Svish
    I am trying to make a method that will go through a list of generic objects and replace all their properties of type string which is either null or empty with a replacement. How is a good way to do this? I have this kind of... shell... so far: public static void ReplaceEmptyStrings<T>(List<T> list, string replacement) { var properties = typeof(T).GetProperties( -- What BindingFlags? -- ); foreach(var p in properties) { foreach(var item in list) { if(string.IsNullOrEmpty((string) p.GetValue(item, null))) p.SetValue(item, replacement, null); } } } So, how do I find all the properties of a type that are: Of type string Has public get Has public set ? I made this test class: class TestSubject { public string Public; private string Private; public string PublicPublic { get; set; } public string PublicPrivate { get; private set; } public string PrivatePublic { private get; set; } private string PrivatePrivate { get; set; } } The following does not work: var properties = typeof(TestSubject) .GetProperties(BindingFlags.Instance|BindingFlags.Public) .Where(ø => ø.CanRead && ø.CanWrite) .Where(ø => ø.PropertyType == typeof(string)); If I print out the Name of those properties I get there, I get: PublicPublic PublicPrivate PrivatePublic In other words, I get two properties too much. Note: This could probably be done in a better way... using nested foreach and reflection and all here... but if you have any great alternative ideas, please let me know cause I want to learn!

    Read the article

  • How to queue and call actual methods (rather than immediately eval) in java?

    - by alleywayjack
    There are a list of tasks that are time sensitive (but "time" in this case is arbitrary to what another program tells me - it's more like "ticks" rather than time). However, I do NOT want said methods to evaluate immediately. I want one to execute after the other finished. I'm using a linked list for my queue, but I'm not really sure how/if I can access the actual methods in a class without evaluating them immediate. The code would look something like... LinkedList<Method> l = new LinkedList<Method>(); l.add( this.move(4) ); l.add( this.read() ); l.removeFirst().call(); //wait 80 ticks l.removeFirst().call(); move(4) would execute immediately, then 80 ticks later, I would remove it from the list and call this.read() which would then be executed. I'm assuming this has to do with the reflection classes, and I've poked around a bit, but I can't seem to get anything to work, or do what I want. If only I could use pointers...

    Read the article

  • Best loose way to get objects with common base class

    - by Michael Teper
    I struggled to come up with a good title for this question, so suggestions are welcome. Let's say we have an abstract base class ActionBase that looks something like this: public abstract class ActionBase { public abstract string Name { get; } public abstract string Description { get; } // rest of declaration follows } And we have a bunch of different actions defined, like a MoveFileAction, WriteToRegistryAction, etc. These actions get attached to Worker objects: public class Worker { private IList<ActionBase> _actions = new List<ActionBase>(); public IList<ActionBase> Actions { get { return _actions; } } // worker stuff ... } So far, pretty straight-forward. Now, I'd like to have a UI for setting up Workers, assigning Actions, setting properties, and so on. In this UI, I want to present a list of all available actions, along with their properties, and for that I'd want to first gather up all the names and descriptions of available actions (plus the type) into a collection of the following type of item: public class ActionDescriptor { public string Name { get; } public string Description { get; } poblic Type Type { get; } } Certainly, I can use reflection to do this, but is there a better way? Having Name and Description be instance properties of ActionBase (as opposed to statics on derived classes) smells a bit, but there isn't an abstract static in C#. Thank you!

    Read the article

  • Suggestions on Working with this Inherited Generic Method

    - by blu
    We have inherited a project that is a wrapper around a section of the core business model. There is one method that takes a generic, finds items matching that type from a member and then returns a list of that type. public List<T> GetFoos<T>() { List<IFoo> matches = Foos.FindAll( f => f.GetType() == typeof(T) ); List<T> resultList = new List<T>(); foreach (var match in matches) { resultList.Add((T)obj); } } Foos can hold the same object cast into various classes in inheritance hierarchy to aggregate totals differently for different UI presentations. There are 20+ different types of descendants that can be returned by GetFoos. The existing code basically has a big switch statement copied and pasted throughout the code. The code in each section calls GetFoos with its corresponding type. We are currently refactoring that into one consolidated area, but as we are doing that we are looking at other ways to work with this method. One thought was to use reflection to pass in the type, and that worked great until we realized the Invoke returned an object, and that it needed to be cast somehow to the List <T>. Another was to just use the switch statement until 4.0 and then use the dynamic language options. We welcome any alternate thoughts on how we can work with this method. I have left the code pretty brief, but if you'd like to know any additional details please just ask.

    Read the article

  • Get parameter values from method at run time

    - by Landin Martens
    I have the current method example: public void MethodName(string param1,int param2) { object[] obj = new object[] { (object) param1, (object) param2 }; //Code to that uses this array to invoke dynamic methods } Is there a dynamic way (I am guessing using reflection) that will get the current executing method parameter values and place them in a object array? I have read that you can get parameter information using MethodBase and MethodInfo but those only have information about the parameter and not the value it self which is what I need. So for example if I pass "test" and 1 as method parameters without coding for the specific parameters can I get a object array with two indexes { "test", 1 }? I would really like to not have to use a third party API, but if it has source code for that API then I will accept that as an answer as long as its not a huge API and there is no simple way to do it without this API. I am sure there must be a way, maybe using the stack, who knows. You guys are the experts and that is why I come here. Thank you in advance, I can't wait to see how this is done. EDIT It may not be clear so here some extra information. This code example is just that, an example to show what I want. It would be to bloated and big to show the actual code where it is needed but the question is how to get the array without manually creating one. I need to some how get the values and place them in a array without coding the specific parameters.

    Read the article

  • Type contraint problem of C#

    - by user351565
    I meet a problem about type contraint of c# now. I wrote a pair of methods that can convert object to string and convert string to object. ex. static string ConvertToString(Type type, object val) { if (type == typeof(string)) return (string)val; if (type == typeof(int)) return val.ToString(); if (type.InSubclassOf(typeof(CodeObject))) return ((CodeObject)val).Code; } static T ConvertToObject<T>(string str) { Type type = typeof(T); if (type == typeof(string)) return (T)(object)val; if (type == typeof(int)) return (T)(object)int.Parse(val); if (type.InSubclassOf(typeof(CodeObject))) return Codes.Get<T>(val); } where CodeObject is a base class of Employees, Offices ..., which can fetch by static method Godes.Get where T: CodeObject but the code above cannot be compiled because error #CS0314 the generic type T of method ConvertToObject have no any constraint but Codes.Get request T must be subclass of CodeObject i tried use overloading to solve the problem but not ok. is there any way to clear up the problem? like reflection?

    Read the article

  • What might cause this ExecutionEngineException?

    - by Qwertie
    I am trying to use Reflection.Emit to generate a wrapper class in a dynamic assembly. Automatic wrapper generation is part of a new open-source library I'm writing called "GoInterfaces". The wrapper class implements IEnumerable<string> and wraps List<string>. In C# terms, all it does is this: class List1_7931B0B4_79328AA0 : IEnumerable<string> { private readonly List<string> _obj; public List1_7931B0B4_79328AA0(List<string> obj) { this._obj = obj; } IEnumerator IEnumerable.GetEnumerator() { return this._obj.GetEnumerator(); } public sealed IEnumerator<string> GetEnumerator() { return this._obj.GetEnumerator(); } } However, when I try to call the GetEnumerator() method on my wrapper class, I get ExecutionEngineException. So I saved my dynamic assembly to a DLL and used ildasm on it. Is there anything wrong with the following code? .class public auto ansi sealed List`1_7931B0B4_79328AA0 extends [mscorlib]System.Object implements [mscorlib]System.Collections.Generic.IEnumerable`1<string>, [Loyc.Runtime]Loyc.Runtime.IGoInterfaceWrapper { .field private initonly class [mscorlib]System.Collections.Generic.List`1<string> _obj .method public hidebysig virtual final instance class [mscorlib]System.Collections.Generic.IEnumerator`1<string> GetEnumerator() cil managed { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> List`1_7931B0B4_79328AA0::_obj IL_0006: call instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator() IL_000b: ret } // end of method List`1_7931B0B4_79328AA0::GetEnumerator .method public hidebysig virtual final instance class [mscorlib]System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() cil managed { .override [mscorlib]System.Collections.IEnumerable::GetEnumerator // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld class [mscorlib]System.Collections.Generic.List`1<string> List`1_7931B0B4_79328AA0::_obj IL_0006: call instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator() IL_000b: ret } // end of method List`1_7931B0B4_79328AA0::System.Collections.IEnumerable.GetEnumerator ... I have a test suite that wraps all sorts of different things, including interfaces derived from other interfaces, and multiple interface methods with identical signatures. It's only when I try to wrap IEnumerable<T> that this problem occurs. I'd be happy to send the source code (2 *.cs files, no dependencies) if anyone would like.

    Read the article

  • RuntimeBinderException with dynamic in C# 4.0

    - by Terence Lewis
    I have an interface: public abstract class Authorizer<T> where T : RequiresAuthorization { public AuthorizationStatus Authorize(T record) { // Perform authorization specific stuff // and then hand off to an abstract method to handle T-specific stuff // that should happen when authorization is successful } } Then, I have a bunch of different classes which all implement RequiresAuthorization, and correspondingly, an Authorizer<T> for each of them (each business object in my domain requires different logic to execute once the record has been authorized). I'm also using a UnityContainer, in which I register various Authorizer<T>'s. I then have some code as follows to find the right record out of the database and authorize it: void Authorize(RequiresAuthorization item) { var dbItem = ChildContainer.Resolve<IAuthorizationRepository>() .RetrieveRequiresAuthorizationById(item.Id); var authorizerType = type.GetType(String.Format("Foo.Authorizer`1[[{0}]], Foo", dbItem.GetType().AssemblyQualifiedName)); dynamic authorizer = ChildContainer.Resolve(type) as dynamic; authorizer.Authorize(dbItem); } Basically, I'm using the Id on the object to retrieve it out of the database. In the background NHibernate takes care of figuring out what type of RequiresAuthorization it is. I then want to find the right Authorizer for it (I don't know at compile time what implementation of Authorizer<T> I need, so I've got a little bit of reflection to get the fully qualified type). To accomplish this, I use the non-generic overload of UnityContainer's Resolve method to look up the correct authorizer from configuration. Finally, I want to call Authorize on the authorizer, passing through the object I've gotten back from NHibernate. Now, for the problem: In Beta2 of VS2010 the above code works perfectly. On RC and RTM, as soon as I make the Authorize() call, I get a RuntimeBinderException saying "The best overloaded method match for 'Foo.Authorizer<Bar>.Authorize(Bar)' has some invalid arguments". When I inspect the authorizer in the debugger, it's the correct type. When I call GetType().GetMethods() on it, I can see the Authorize method which takes a Bar. If I do GetType() on dbItem it is a Bar. Because this worked in Beta2 and not in RC, I assumed it was a regression (it seems like it should work) and I delayed sorting it out until after I'd had a chance to test it on the RTM version of C# 4.0. Now I've done that and the problem still persists. Does anybody have any suggestions to make this work? Thanks Terence

    Read the article

  • Which Activator.CreateInstance overload function to call?

    - by user299990
    Which Activator.CreateInstance overload function to call? I have a type returned from "Type proxyType = GetProxyType(contractType);" and the constructorinfo is "[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext)} base {System.Reflection.MemberInfo} = {Void .ctor(System.ServiceModel.InstanceContext)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)} [System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)} base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)}. Thanks!!

    Read the article

  • Where can I find information on the Get, Set and Address methods for multidimensional System.Array i

    - by Rob Smallshire
    System.Array serves as the base class for all arrays in the Common Language Runtime (CLR). According to this article, For each concrete array type, [the] runtime adds three special methods: Get/Set/Address. and indeed if I disassemble this C# code, int[,] x = new int[1024,1024]; x[0,0] = 1; x[1,1] = 2; x[2,2] = 3; Console.WriteLine(x[0,0]); Console.WriteLine(x[1,1]); Console.WriteLine(x[2,2]); into CIL I get, IL_0000: ldc.i4 0x400 IL_0005: ldc.i4 0x400 IL_000a: newobj instance void int32[0...,0...]::.ctor(int32, int32) IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: ldc.i4.0 IL_0012: ldc.i4.0 IL_0013: ldc.i4.1 IL_0014: call instance void int32[0...,0...]::Set(int32, int32, int32) IL_0019: ldloc.0 IL_001a: ldc.i4.1 IL_001b: ldc.i4.1 IL_001c: ldc.i4.2 IL_001d: call instance void int32[0...,0...]::Set(int32, int32, int32) IL_0022: ldloc.0 IL_0023: ldc.i4.2 IL_0024: ldc.i4.2 IL_0025: ldc.i4.3 IL_0026: call instance void int32[0...,0...]::Set(int32, int32, int32) IL_002b: ldloc.0 IL_002c: ldc.i4.0 IL_002d: ldc.i4.0 IL_002e: call instance int32 int32[0...,0...]::Get(int32, int32) IL_0033: call void [mscorlib]System.Console::WriteLine(int32) IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: ldc.i4.1 IL_003b: call instance int32 int32[0...,0...]::Get(int32, int32) IL_0040: call void [mscorlib]System.Console::WriteLine(int32) IL_0045: ldloc.0 IL_0046: ldc.i4.2 IL_0047: ldc.i4.2 IL_0048: call instance int32 int32[0...,0...]::Get(int32, int32) IL_004d: call void [mscorlib]System.Console::WriteLine(int32) where the calls to the aforementioned Get and Set methods can be clearly seen. It seems the arity of these methods is related to the dimensionality of the array, which is presumably why they are created by the runtime and are not pre-declared. I couldn't locate any information about these methods on MSDN and their simple names makes them resistant to Googling. I'm writing a compiler for a language which supports multidimensional arrays, so I'd like to find some official documentation about these methods, under what conditions I can expect them to exist and what I can expect their signatures to be. In particular, I'd like to know whether its possible to get a MethodInfo object for Get or Set for use with Reflection.Emit without having to create an instance of the array with correct type and dimensionality on which to reflect, as is done in the linked example.

    Read the article

  • Different behavior of reflected generic delegates with and without debugger

    - by Andrew_B
    Hello. We have encountered some strange things while calling reflected generic delegates. In some cases with attatched debuger we can make impossible call, while without debugger we cannot catch any exception and application fastfails. Here is the code: using System; using System.Windows.Forms; using System.Reflection; namespace GenericDelegate { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private delegate Class2 Delegate1(); private void button1_Click(object sender, EventArgs e) { MethodInfo mi = typeof (Class1<>).GetMethod("GetClass", BindingFlags.NonPublic | BindingFlags.Static); if (mi != null) { Delegate1 del = (Delegate1) Delegate.CreateDelegate(typeof (Delegate1), mi); MessageBox.Show("1"); try { del(); } catch (Exception) { MessageBox.Show("No, I can`t catch it"); } MessageBox.Show("2"); mi.Invoke(null, new object[] {});//It's Ok, we'll get exception here MessageBox.Show("3"); } } class Class2 { } class Class1<T> : Class2 { internal static Class2 GetClass() { Type type = typeof(T); MessageBox.Show("Type name " + type.FullName +" Type: " + type + " Assembly " + type.Assembly); return new Class1<T>(); } } } } There are two problems: Behavior differs with debugger and without You cannot catch this error without debugger by clr tricks. It's just not the clr exception. There are memory acces vialation, reading zero pointer inside of internal code. Use case: You develop something like plugins system for your app. You read external assembly, find suitable method in some type, and execute it. And we just forgot about that we need to check up is the type generic or not. Under VS (and .net from 2.0 to 4.0) everything works fine. Called function does not uses static context of generic type and type parameters. But without VS application fails with no sound. We even cannot identify call stack attaching debuger. Tested with .net 4.0 The question is why VS catches but runtime do not?

    Read the article

  • How to reflect over T to build an expression tree for a query?

    - by Alex
    Hi all, I'm trying to build a generic class to work with entities from EF. This class talks to repositories, but it's this class that creates the expressions sent to the repositories. Anyway, I'm just trying to implement one virtual method that will act as a base for common querying. Specifically, it will accept a an int and it only needs to perform a query over the primary key of the entity in question. I've been screwing around with it and I've built a reflection which may or may not work. I say that because I get a NotSupportedException with a message of LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression. So then I tried another approach and it produced the same exception but with the error of The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities. I know it's because EF will not parse the expression the way L2S will. Anyway, I'm hopping someone with a bit more experience can point me into the right direction on this. I'm posting the entire class with both attempts I've made. public class Provider<T> where T : class { protected readonly Repository<T> Repository = null; private readonly string TEntityName = typeof(T).Name; [Inject] public Provider( Repository<T> Repository) { this.Repository = Repository; } public virtual void Add( T TEntity) { this.Repository.Insert(TEntity); } public virtual T Get( int PrimaryKey) { // The LINQ expression node type 'ArrayIndex' is not supported in // LINQ to Entities. return this.Repository.Select( t => (((int)(t as EntityObject).EntityKey.EntityKeyValues[0].Value) == PrimaryKey)).Single(); // LINQ to Entities does not recognize the method // 'System.Object GetValue(System.Object, System.Object[])' method, // and this method cannot be translated into a store expression. return this.Repository.Select( t => (((int)t.GetType().GetProperties().Single( p => (p.Name == (this.TEntityName + "Id"))).GetValue(t, null)) == PrimaryKey)).Single(); } public virtual IList<T> GetAll() { return this.Repository.Select().ToList(); } protected virtual void Save() { this.Repository.Update(); } }

    Read the article

  • C# 'could not found' existing method

    - by shybovycha
    Greetings! I've been fooling around (a bit) with C# and its assemblies. And so i've found such an interesting feature as dynamic loading assemblies and invoking its class members. A bit of google and here i am, writing some kind of 'assembly explorer'. (i've used some portions of code from here, here and here and none of 'em gave any of expected results). But i've found a small bug: when i tried to invoke class method from assembly i've loaded, application raised MissingMethod exception. I'm sure DLL i'm loading contains class and method i'm tryin' to invoke (my app ensures me as well as RedGate's .NET Reflector): The main application code seems to be okay and i start thinking if i was wrong with my DLL... Ah, and i've put both of projects into one solution, but i don't think it may cause any troubles. And yes, DLL project has 'class library' target while the main application one has 'console applcation' target. So, the question is: what's wrong with 'em? Here are some source code: DLL source: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassLibrary1 { public class Class1 { public void Main() { System.Console.WriteLine("Hello, World!"); } } } Main application source: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Assembly asm = Assembly.LoadFrom(@"a\long\long\path\ClassLibrary1.dll"); try { foreach (Type t in asm.GetTypes()) { if (t.IsClass == true && t.FullName.EndsWith(".Class1")) { object obj = Activator.CreateInstance(t); object res = t.InvokeMember("Main", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, null); // Exception is risen from here } } } catch (Exception e) { System.Console.WriteLine("Error: {0}", e.Message); } System.Console.ReadKey(); } } } UPD: worked for one case - when DLL method takes no arguments: DLL class (also works if method is not static): public class Class1 { public static void Main() { System.Console.WriteLine("Hello, World!"); } } Method invoke code: object res = t.InvokeMember("Main", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null);

    Read the article

  • Dynamic swappable Data Access Layer

    - by Andy
    I'm writing a data driven WPF client. The client will typically pull data from a WCF service, which queries a SQL db, but I'd like the option to pull the data directly from SQL or other arbitrary data sources. I've come up with this design and would like to hear your opinion on whether it is the best design. First, we have some data object we'd like to extract from SQL. // The Data Object with a single property public class Customer { private string m_Name = string.Empty; public string Name { get { return m_Name; } set { m_Name = value;} } } Then I plan on using an interface which all data access layers should implement. Suppose one could also use an abstract class. Thoughts? // The interface with a single method interface ICustomerFacade { List<Customer> GetAll(); } One can create a SQL implementation. // Sql Implementation public class SqlCustomrFacade : ICustomerFacade { public List<Customer> GetAll() { // Query SQL db and return something useful // ... return new List<Customer>(); } } We can also create a WCF implementation. The problem with WCF is is that it doesn't use the same data object. It creates its own local version, so we would have to copy the details over somehow. I suppose one could use reflection to copy the values of similar fields across. Thoughts? // Wcf Implementation public class WcfCustomrFacade : ICustomerFacade { public List<Customer> GetAll() { // Get date from the Wcf Service (not defined here) List<WcfService.Customer> wcfCustomers = wcfService.GetAllCustomers(); // The list we're going to return List<Customer> customers = new List<Customer>(); // This is horrible foreach(WcfService.Customer wcfCustomer in wcfCustomers) { Customer customer = new Customer(); customer.Name = wcfCustomer.Name; customers.Add(customer); } return customers; } } I also plan on using a factory to decide which facade to use. // Factory pattern public class FacadeFactory() { public static ICustomerFacade CreateCustomerFacade() { // Determine the facade to use if (ConfigurationManager.AppSettings["DAL"] == "Sql") return new SqlCustomrFacade(); else return new WcfCustomrFacade(); } } This is how the DAL would typically be used. // Test application public class MyApp { public static void Main() { ICustomerFacade cf = FacadeFactory.CreateCustomerFacade(); cf.GetAll(); } } I appreciate your thoughts and time.

    Read the article

  • Object validator - is this good design?

    - by neo2862
    I'm working on a project where the API methods I write have to return different "views" of domain objects, like this: namespace View.Product { public class SearchResult : View { public string Name { get; set; } public decimal Price { get; set; } } public class Profile : View { public string Name { get; set; } public decimal Price { get; set; } [UseValidationRuleset("FreeText")] public string Description { get; set; } [SuppressValidation] public string Comment { get; set; } } } These are also the arguments of setter methods in the API which have to be validated before storing them in the DB. I wrote an object validator that lets the user define validation rulesets in an XML file and checks if an object conforms to those rules: [Validatable] public class View { [SuppressValidation] public ValidationError[] ValidationErrors { get { return Validator.Validate(this); } } } public static class Validator { private static Dictionary<string, Ruleset> Rulesets; static Validator() { // read rulesets from xml } public static ValidationError[] Validate(object obj) { // check if obj is decorated with ValidatableAttribute // if not, return an empty array (successful validation) // iterate over the properties of obj // - if the property is decorated with SuppressValidationAttribute, // continue // - if it is decorated with UseValidationRulesetAttribute, // use the ruleset specified to call // Validate(object value, string rulesetName, string FieldName) // - otherwise, get the name of the property using reflection and // use that as the ruleset name } private static List<ValidationError> Validate(object obj, string fieldName, string rulesetName) { // check if the ruleset exists, if not, throw exception // call the ruleset's Validate method and return the results } } public class Ruleset { public Type Type { get; set; } public Rule[] Rules { get; set; } public List<ValidationError> Validate(object property, string propertyName) { // check if property is of type Type // if not, throw exception // iterate over the Rules and call their Validate methods // return a list of their return values } } public abstract class Rule { public Type Type { get; protected set; } public abstract ValidationError Validate(object value, string propertyName); } public class StringRegexRule : Rule { public string Regex { get; set; } public StringRegexRule() { Type = typeof(string); } public override ValidationError Validate(object value, string propertyName) { // see if Regex matches value and return // null or a ValidationError } } Phew... Thanks for reading all of this. I've already implemented it and it works nicely, and I'm planning to extend it to validate the contents of IEnumerable fields and other fields that are Validatable. What I'm particularly concerned about is that if no ruleset is specified, the validator tries to use the name of the property as the ruleset name. (If you don't want that behavior, you can use [SuppressValidation].) This makes the code much less cluttered (no need to use [UseValidationRuleset("something")] on every single property) but it somehow doesn't feel right. I can't decide if it's awful or awesome. What do you think? Any suggestions on the other parts of this design are welcome too. I'm not very experienced and I'm grateful for any help. Also, is "Validatable" a good name? To me, it sounds pretty weird but I'm not a native English speaker.

    Read the article

  • Getting information of a class structure at runtime using Java reflection

    - by Eliza Sahoo
    A simple way to get the class structure information of the Class we are using in our application. Step1: Create the Class object of the class we want to explore at run time or the class which is getting added at runtime. Step2: As we are looking for the structure of the class, get all Constructors, Fields and methods by invoking respective functions of the Class. Step3: print them in java console or use them as required. Eliza

    Read the article

  • Weird result comparing property values using reflection

    - by Brian
    Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework. The objects entity and defaultEntity were created using Activator.CreateInstance(); Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) false

    Read the article

  • How to recursively serialize an object using reflection ?

    - by Tony
    I want to navigate to the N-th level of an object, and serialize it's properties in String format. For Example: class Animal { public String name; public int weight; public Animal friend; public Set<Animal> children = new HashSet<Animal>() ; } should be serialized like this: {name:"Monkey", weight:200, friend:{name:"Monkey Friend",weight:300 ,children:{...if has children}}, children:{name:"MonkeyChild1",weight:100,children:{... recursively nested}} } And you may probably notice that it is similar to serializing an object to json. I know there're many libs can do this, can you give me some instructive ideas on how to write this?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >