I am fairly new to reflection and I would like to know, if possible, how to create an instance of a class then add properties to the class, set those properties, then read them later. I don't have any code as i don't even know how to start going about this. C# or VB is fine.
Thank You
EDIT: (to elaborate)
My system has a dynamic form creator. one of my associates requires that the form data be accessible via web service. My idea was to create a class (based on the dynamic form) add properties to the class (based on the forms fields) set those properties (based on the values input for those fields) then return the class in the web service.
additionally, the web service will be able to set the properties in the class and eventually commit those changes to the db.
If you mean dynamically create a class, then the two options are:
Reflection.Emit - Difficult, Fast to create the class
CodeDom - Less Difficult, Slower to create the class
If you mean create an instance of an existing class, then start with Activator.CreateInstance to create an instance of the object, and then look at the methods on Type such as GetProperty which will return a PropertyInfo that you can call GetValue and SetValue on.
Update: For the scenario you describe, returning dynamic data from a web service, then I'd recommend against this approach as it's hard for you to code, and hard for statically-typed languages to consume. Instead, as suggested in the comments and one of the other answers, some sort of dictionary would likely be a better option.
(Note that when I say return some sort of dictionary, I am speaking figuratively rather than literally, i.e. return something which is conceptually the same as a dictionary such as a list of key-value pairs. I wouldn't recommend directly returning one (even if you're using WCF which does support this) because it's typically better to have full control over the XML you return.)
I know this is being overly simplified by why not just KISS and generate the required Xml to return through the Web Service and then parse the returned Xml to populate the database.
My reasoning is that for the expanded reason you suggest doing this I can see the value or reason for wanting a dynamic class?
The Execution-Time Code Generation chapter of Eric Gunnerson's book (A Programmer's Introduction to C#) has some great information on this topic. See page 14 and onwards in particular. He outlines the two main methods of accomplishing dynamic class/code generation (CodeDOM and the Reflection.Emit namespace). It also discusses the difficulty and performance of the two approaches. Have a read through that, and you ought to find everything you might need.
The real question is, what do you need to use those properties for?
What are gonna be the use cases? Do you need to bind those properties to the UI somehow? Using what kind of technology? (WPF, Windows Forms?)
Is it just that you need to gather a set of key/value pairs at runtime? Then maybe a simple dictionary would do the trick.
Please elaborate if you can on what it is you need, and I'm sure people here can come up with plenty of ways to help you, but it's difficult to give a good answer without more context.
Related
Background:
I have 2 instances of an object of the same type. One object is populated with the configuration of a device I'm connected to, the other object is populated with a version of the configuration that I've stored on my hard drive.
The user can alter either, so I'd like to compare them and present the differences to the user.
Each object contains a number of ViewModel properties, all of which extend ViewModelBase, which are the ones I want to compare.
Question:
Is a better way to do this than what I'm about to propose.
I'm thinking of using Reflection to inspect each property in my objects, and for each that extend ViewModelBase, I'll loop through each of those properties. For any that are different, I'll put the name and value into a list and then present that to the user.
Rather than inventing this wheel, I'm wondering if this is this a problem that's been solved before? Is there a better way for it to be done?
Depending on the amount of properties to be compared, manual checking would be the more efficient option. However, if you have lots of properties or want the check to be dynamic (i.e. you just add new properties and it automagically works), then I think Reflection is the way to go here.
Why not just implement the equals operator for your type?
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
Edit: Having read more carefully I see what you're actually asking is what the most efficient way of doing the actual comparison is.
Doing it via reflection saves on code but is slower. Doing it with lots of manual comparions is fairly quick but more code.
If you are fairly determent and lazy in the good way. You can mix benefits of both solutions. With help of tool like cci you can emit method that compares properties. The beauty of this is that your reflection code will be executed on compile time leaving you with strait forward method to execute at runtime. This allows you to change models as you see fit and not worry about comparison code. There is a down side to this and that is learning cci which is quite challenging.
I'm about to build a search page on a website and the search is going to be extensive with a couple of models and with each model having a lot of properties.
Is there a way to do this in a generic way or use reflector as I have seen in some posts? I need some pointers or tips on how to aproach this. Highly appreciate it.
You can use reflection to get the information you need. If you have a type T you can use
typeof(T).GetProperties()
to get all public properties. Same is possible for fields, methods, ... If you need more meta data to generate your search, you can use attributes to annotate the properties (or fields, methods, ...) That's the way I would get started. Further details depend on your exact use case.
Can you give more details?
What is the purpose of your search? Give me the 30 second version so I can understand where you are going with this.
Are you planning on using RegEx and word stemming?
What kinds of values count as matches?
I assume you only want to search properties on the objects/models. Right?
Do want to see every property or only some of them?
What kinds of data is stored in the properties? (string, byte[], enum, etc)
Brainstorming Ideas:
What about searching one the DB server-side instead of in your hydrated objects? It might be faster (at run-time) to leverage your DB than load all of the objects into memory then reflect upon them.
You could also write a method that supports your search within the context of the model itself. You pass in the search rule set as an expression then find the match. If you have some kind of a collection container, the search could be run at that level against all of the objects in the collection.
If you want some reflection code, I wrote something that shows a lot of info about an object via reflection. I wrote this a long while ago (Dec 2009). I'm not sure if it does what you want. Take a look. If it works for you, use it! (Link)
What are the best way to store variables in a silverlight application?
Need to transfer store a customer ID throught the application but im not sure what is the best way
Disclaimer: This is a purely subjective answer. Others might object or have better suggestions.
I work mostly in VB.NET and over there, we've got the My.Application namespace where we can keep global variables. VB.NET users also have the option of using a Module for such purposes.
A Module, if I remember right, is equivalent to a static sealed class in C# so you can essentially do something of that sort.
To replicate VB.NET's functionality when I work in C#, I create a static class, with access level set to internal so its members are accessible from within the entire application.
Thus, when I assign a value to a member of the static class, it is accessible from all other classes in the application.
Hope this helps
Store the variable in a place where those things that need to get to it, can; and those things that don't need to get to it, can't. Can't say anything more specific without more information.
If you were following an MVVM pattern then I would have said as a property of the Customer model, with an instance of the customer model being accessed via the ViewModel.
Even if you aren't I would say within the application code and use binding where its needed in the UI. Otherwise you run the risk of changes to your UI causing the loss of customer ID storage at somepoint in the future.
If needed in more than one place then just create a repository that stores all of your data and have that accessed as needed (this way you can decouple your UIs from each other even if they use the same data source.
You may look at using InitParams, without knowing the situation I can't say much more.
http://msdn.microsoft.com/en-us/library/cc838255(VS.95).aspx
Is it possible to create objects at designtime without having to have hard coded class definitions, then populate properties with primitives or even strongly typed data types?
This might sound confusing, so I will attempt to give you a use case scenario.
Use case:
You have an XML config file that could hold configuration values for connecting to various systems in an SOA application. In C# the XML file is read, but for each system the configuration properties are different (e.g: SQL might have a connection string, while SharePoint might need a username + password + domain + url, while yet an smtp server would need username + password + port + url)
So instead of creating static classes as follows
public class SharePointConfiguration or public class SQLConfiguration, then have each class with custom properties (this is cumbersome)
or
using a 1990's method, an ArrayList or some named collection
Is there not a more preferred way to achieve this? Taking advantage of new language features, that can still offer design time intellisense, which would make the code easier to maintain and less prone to error.
I guess I am looking for some kind of multipurpose .net 4 property holder.
Thanks
Use this sample implementation of a PropertyBag.
If property doesn't exist, create it on the fly...
http://www.codeproject.com/KB/recipes/propertybag.aspx
If you want emit code at runtime?
Checkout the Reflection.Emit namespace
OR better
RunSharp - nicer API
What you want is XML, based on a schema. This will give you IntelliSense, including code snippets, at the same time as providing flexibility.
Based on your question (and assuming I'm reading it right), that would be impossible. The closest you could get would be to use the 'dynamic' type and assign your values to properties at runtime on it - the problem being, that dynamic has no Intellisense support, and even with some other kind of solution, the Intellisense would not be available because the properties would only be attached at runtime.
Am I confused on what you are asking?
I think I have my brain halfway wrapped around the Dynamic Types concept in C# 4, but can't for the life of me figure out a scenario where I'd actually want to use it.
I'm sure there are many, but I'm just having trouble making the connection as to how I could engineer a solution that is better solved with dynamics as opposed to interfaces, dependency injection, etc.
So, what's a real-world application scenario where dynamic type usage is appropriate?
There are lots of cases where you are already using dynamic typing and dynamic binding today. You just don't realize it, because it is all hidden behind strings or System.Object, since until C# 4, the necessary support wasn't there.
One example is COM interop: COM is actually a semi-dynamic object system. When you do COM interop, a lot of methods actually return a dynamic object, but because C# didn't support them, they were returned as System.Object and you had to cast them yourself, possibly catching exceptions on the way.
Another example is interacting with dynamically typed (or even untyped) data, such as JSON, CSV, HTML, schemaless XML, schemaless web services, schemaless databases (which are, after all, the new hotness). Today, you use strings for those. An XML API would look like
var doc = new XmlDocument("/path/to/file.xml");
var baz = doc.GetElement("foo").GetElement("qux");
and so on. But how about:
dynamic doc = new XmlDocument("/path/to/file.xml");
var baz = doc.foo.qux;
Doesn't that look nice?
A third example is reflection. Today, invocation of a method via reflection is done by passing a string to InvokeMember (or whatever the thing is called). Wouldn't it be nicer to, you know, just invoke the damn thing?
Then, there is generation of dynamic data (basically the opposite of the second example). Here's an example how to generate some dynamic XML:
dynamic doc = new XmlBuilder();
doc.articles(id=42, type="List", () => {
article(() => {
number(42);
title("blahblubb");});});
This is not nearly as beautiful as the equivalent Ruby, but it is the best I could come up with at such short notice :-)
And last but certainly not least, integration with a dynamically typed language. Whether that is JavaScript in a Silverlight application, a custom rules engine embedded in your business app or a DLR instance that you host in your CAD program/IDE/text editor.
There's one example on MSDN:
Many COM methods allow for variation in argument types and return type by designating the types as object. This has necessitated explicit casting of the values to coordinate with strongly typed variables in C#. If you compile by using the /link (C# Compiler Options) option, the introduction of the dynamic type enables you to treat the occurrences of object in COM signatures as if they were of type dynamic, and thereby to avoid much of the casting.
Another example is if you have to interop with dynamic languages.
Also there are some occasions where you want to make some code generic but you can't because even though the objects implement the same method, they don't share a suitable base class or interface that declares the methods you need. An example of this is trying to make something generic with ints and short. It's a bit of a hack, but dynamic allows you to call the same methods on these different types, allowing more code reuse.
Update: A bit of searching on here found this related post.
From Walter Almeida's Blog: a scenario of use of the dynamic keyword in C# to enhance object orientation:
http://blog.walteralmeida.com/2010/05/using-the-dynamic-keyword-in-c-to-improve-objectorientation.html
Scott Watermasysk wrote an article about using dynamics for dictionary key-property mapping on the MongoDB C# driver.
http://simpable.com/code/mongodb-dynamics/
I think others have given some great answers so far so I just want to add this example by David Hanson. Hist post shows the most practical application I've found so far for dynamic types in C# where he uses them to create proxy objects. In this example he creates a proxy which allows raising of exceptions on WPF binding errors. I'm not sure if this could also be achieved in the case of WPF bindings by using CustomTypeDescriptors and property descriptor concepts in general but regardless I think the use of the new C# 4.0 dynamic type is a great demonstration of its capabilities.
Raising binding exceptions in WPF & Silverlight with .net 4.0 Dynamics
One other use that I can think of for Dynamic types is to create proxies that similarly can be plugged in as a DataContext in WPF or in other places where a generic object type is expected and reflection methods are normally used to interrogate the type. In these cases especially when building tests a dynamic type can be used which would then allow property accessors to be called and logged accordingly by the proxy object in a dynamic fashion without having to hardcode properties within a test-only class.
I read an interesting article about this (attached) by Scott Hanselman. He points out that as opposed to using object you can use dynamic to reference methods from older COM objects where the compiler doesn't know a method exists. I found the link useful.
Scott Hanselman - C#4 and the dynamic keyword