How to serialize attached properties - c#

I am writing .NET3.5, WPF application using Composite Application Library. Application is divided into several modules.
In infrastructure module I have defined NetworkNode object. The Network module manages a collection of NetworkNodes and uses XmlSerializer to store/load this collection. So far everythings works.
But I have other modules e.g NodeModule. If a NetworkNode was selected in Network module, an event is published to other modules using EventAggregator. These modules can attach various information to the NetworkNode using attached properties.
The problem is the NetworkModule does not know about the other modules, therefor these properties are not serialized. It is possible to somehow list and serialize all properties attached to an object? Or do I have to change the concept and use something else than attached properties?
Regards

You can list all dependency properties (attached or not) defined on an object using DependencyObject.GetLocalValueEnumerator :
LocalValueEnumerator propEnumerator = foo.GetLocalValueEnumerator();
while (propEnumerator.MoveNext())
{
Console.WriteLine ("{0} = {1}",
propEnumerator.Current.Property.Name,
propEnumerator.Current.Value);
}
However, this won't help for XML serialization (unless you implement IXmlSerializable, which is a pain...). You should probably use XamlWriter instead (which I assume is what Drew was talking about, since there is no XamlSerializer...)

Since attached properties aren't visible from a pure CLR perspective, the XmlSerializer has no way to know about them. You would need to switch to use the XamlSerializer architecture in order to be able to serialize both "plain" CLR objects as well as have the special knowledge of DependencyObjects.

If you are using .Net 4.0 (I believe they aren't in .Net 3.5)
You can use either IAttachedPropertyStore or AttachablePropertyServices
Reference Example #1: http://blogs.msdn.com/b/bursteg/archive/2009/05/18/xaml-in-net-4-0-attached-properties-iattachedpropertystore-and-attachablepropertyservices.aspx
Also, generally, the attached property must be defined correctly:
It must be a property of public (or internal works in some scenarios) non-nested type (i.e. it is not declared inside another type), T.
Define a new AttachableMemberIdentifier(T, "MyProperty")
Provide public static methods on T called "SetMyProperty" and "GetMyProperty", i.e. the "MyProperty" part must match your AttachableMemberIdentifier. (You can't use "Foo" as the name in the AttachableMemberIdentifier and call them "SetBar" and "GetBar" because the Xaml serializer stack needs to find them by reflection.) These methods should then leverage AttachablePropertyServices to store the attached property value.
Reference Example #2: http://blogs.msdn.com/b/mwinkle/archive/2009/12/07/attachedproperty-part-2-putting-it-together.aspx

Related

Can not get instance of type derived in F# library correctly

I'm having a problem in my project with using types from F# in C# library.
I have an application which basically consists of the following main parts:
core library (.NET Standard 2.1);
WPF client.
The core library contains all the platform independent logic and view-models and can be used in any kind of UI clients.
The application is designed to be extensible and can plug extensions dynamically before UI is loaded. For now it's just loading DLL's from the specific folder via Assembly.LoadFrom. The only requirement for the dll to be recognized as an extension is to expose special class that derives from the Module or Extension classes that are defined in core library. And it's working perfectly when loading assemblies written in C#.
But I got struggle with very strange behavior when trying to use extension that is written in F#.
Let's say I have an interface IRecognitionProcessor that is defined in my core library. Here are some of it's members:
public interface IRecognitionProcessor
{
string Name { get; }
string Description { get; }
bool ContainsFace(Bitmap bitmap);
FaceDetail[] ExtractDetails(Bitmap bitmap);
/* more members goes here */
}
In my new extension that provides the custom recognition based on EmguCV library for .NET I have a descendant to IRecognitionProcessor that in result will be extracted and stored in special container.
The extension is written in F#, as I've mentioned before. That's a brief example of the implementation:
type EmguFaceRecognition() =
interface IRecognitionProcessor with
member this.Name : string = "EmguCV"
member this.Description : string = "EmguCV face recognition processor"
member this.ContainsFace (bitmap : Bitmap) : bool =
//code goes here
member this.ExtractDetails (bitmap : Bitmap) : FaceDetail array =
//code goes here
// other implementations
It is loaded correctly without any errors, and all the assemblies that come along with it also loaded normally.
The problem arise when I'm fetching all the processors from my attached extensions. Here is the simplified representation of code that describes module and how it provides the processor:
type EmguRecognitionModule() =
inherit RecognitionModule()
override this.GetRecognitionProcessor() : IRecognitionProcessor =
new EmguFaceRecognition() :> IRecognitionProcessor
// more code goes here
When new module is loaded - it's processor being extracted and stored in storage. Both step with instantiating module via Activator.CreateInstance and fetching it's processor via GetRecognitionProcessor method works fine.
This is the method that populates one of my view-model's collection of processors:
public void PopulateRecognitionProcessors(IEnumerable<IRecognitionProcessor> processors, AccessToken accessToken)
{
if (accessToken != _parentAccessToken)
throw new AccessViolationException("Attempt to set recognition processors from outside of the parent");
_recognitionProcessors.Clear();
_recognitionProcessors.AddRange(processors);
SelectedProcessor = _recognitionProcessors.FirstOrDefault();
}
Pretty simple, though it works bad when processors come from F# library. Even if there are processors, the SelectedProcessor property will not be assigned to the first processor at all, it's still null. When I put a breakpoint and tried to observe the properties of the processors stored in the collection - inspection shows none of properties.
Here is the link to example of property inspection I've made in JetBrains Rider.
But when I'm using Evaluate window, I can access all the properties and methods of the object and IntelliSense works perfectly. Link to image with example of evaluation.
This whole situation makes me feel dumb. Just faced this problem first time. Previously, all my attempts to use types defined in F# libraries succeeded. But this one is an exception.
I see that using type derived from the abstract one works nice. But type that implements the interface somehow doesn't.
After playing with F# project settings and recreating the project from scratch I finally managed to resolve the problem - though the origin of the problem is still a mystery.
But still there is a problem with Rider's property inspector that shows only those members that are declared in the interface descendant directly. I'll check out JetBrains support if there are similar issues already posted.
upd
Seems that DisplayMemberPath of the CheckBox (specified in XAML) also couldn't resolve the implemented properties from the instance.

What is Reflection property of a programming language?

Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.

Properties vs. Fields: Need help grasping the uses of Properties over Fields

First off, I have read through a list of postings on this topic and I don't feel I have grasped properties because of what I had come to understand about encapsulation and field modifiers (private, public..ect).
One of the main aspects of C# that I have come to learn is the importance of data protection within your code by the use of encapsulation. I 'thought' I understood that to be because of the ability of the use of the modifiers (private, public, internal, protected). However, after learning about properties I am sort of torn in understanding not only properties uses, but the overall importance/ability of data protection (what I understood as encapsulation) within C#.
To be more specific, everything I have read when I got to properties in C# is that you should try to use them in place of fields when you can because of:
1) they allow you to change the data type when you can't when directly accessing the field directly.
2) they add a level of protection to data access
However, from what I 'thought' I had come to know about the use of field modifiers did #2, it seemed to me that properties just generated additional code unless you had some reason to change the type (#1) - because you are (more or less) creating hidden methods to access fields as opposed to directly.
Then there is the whole modifiers being able to be added to Properties which further complicates my understanding for the need of properties to access data.
I have read a number of chapters from different writers on "properties" and none have really explained a good understanding of properties vs. fields vs. encapsulation (and good programming methods).
Can someone explain:
1) why I would want to use properties instead of fields (especially when it appears I am just adding additional code
2) any tips on recognizing the use of properties and not seeing them as simply methods (with the exception of the get;set being apparent) when tracing other peoples code?
3) Any general rules of thumb when it comes to good programming methods in relation to when to use what?
Thanks and sorry for the long post - I didn't want to just ask a question that has been asked 100x without explaining why I am asking it again.
1) why I would want to use properties
instead of fields (especially when it
appears I am just adding additional
code
You should always use properties where possible. They abstract direct access to the field (which is created for you if you don't create one). Even if the property does nothing other than setting a value, it can protect you later on. Changing a field to a property later is a breaking change, so if you have a public field and want to change it to a public property, you have to recompile all code which originally accessed that field.
2) any tips on recognizing the use of
properties and not seeing them as
simply methods (with the exception of
the get;set being apparent) when
tracing other peoples code?
I'm not totally certain what you are asking, but when tracing over someone else's code, you should always assume that the property is doing something other than just getting and setting a value. Although it's accepted practice to not put large amounts of code in getters and setter, you can't just assume that since it's a property it will behave quickly.
3) Any general rules of thumb when it
comes to good programming methods in
relation to when to use what?
I always use properties to get and set methods where possible. That way I can add code later if I need to check that the value is within certain bounds, not null etc. Without using properties, I have to go back and put those checks in every place I directly accessed the field.
One of the nice things about Properties is that the getter and the setter can have different levels of access. Consider this:
public class MyClass {
public string MyString { get; private set; }
//...other code
}
This property can only be changed from within, say in a constructor. Have a read up on Dependency Injection. Constructor injection and Property injection both deal with setting properties from some form of external configuration. There are many frameworks out there. If you delve into some of these you will get a good feel for properties and their use. Dependency injection will also help you with your 3rd question about good practice.
When looking at other people's code, you can tell whether something is a method or a property because their icons are different. Also, in Intellisence, the first part of a property's summary is the word Property.
You should not worry about the extra code needed for accessing fields via properties, it will be "optimized" away by the JIT compiler (by inlining the code). Except when it is too large to be inlined, but then you needed the extra code anyway.
And the extra code for defining simple properties is also minimal:
public int MyProp { get; set; } // use auto generated field.
When you need to customize you can alway define your own field later.
So you are left with the extra layer of encapsulation / data protection, and that is a good thing.
My rule: expose fields always through properties
While I absolutely dislike directly exposing fields to the public, there's another thing: Fields can't be exposed through Interfaces; Properties can.
There are several reasons why you might want to use Properties over Fields, here are just a couple:
a. By having the following
public string MyProperty { get; private set; }
you are making the property "read only". No one using your code can modify it's value. There are cases where this isn't strictly true (if your property is a list), but these are known and have solutions.
b. If you decide you need to increase the safety of your code use properties:
public string MyProperty
{
get { return _myField; }
set
{
if (!string.IsNullOrEmpty(value))
{
_myField = value;
}
}
}
You can tell they're properties because they don't have (). The compiler will tell you if you try to add brackets.
It's considered good practise to always use properties.
There are many scenarios where using a simple field would not cause damage, but
a Property can be changed more easily later, i.e. if you want to add an event whenever the value changes or want to perform some value/range checking.
Also, If you have several projects that depend on each other you have to recompile all that depend on the one where a field was changed to a property.
Using fields is usually practiced in private classes that is not intended to share data with other classes, When we want our data to be accessible by other classes we use properties which has the ability to share data with other classes through get and set which are access methods called Auto Properties that have access to data in private classes, also you can use both with access modifiers Full Property in the same class allowing the class to use data privately as data field and in the same time link the private field to a property that makes the data accessible to other classes as well, see this simple example:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
The private string _name is used by the class only, while the Name property is accessible by other classes in the same namespace.
why I would want to use properties instead of fields (especially when it appears I am just adding additional code
You want to use properties over fields becuase, when you use properties you can use events with them, so in a case when you want to do some action when a property changes, you can bind some handlers to PropertyChanging or PropertyChanged events. In case of fields this is not possible. Fields can either be public or private or protected, in case of props you can make them read-only publicly but writable privately.
any tips on recognizing the use of properties and not seeing them as simply methods (with the exception of the get;set being apparent) when tracing other peoples code?
A method should be used when the return value is expected to be dynamic every-time you call, a property should be used when the return value is not that greatly dynamic.
Any general rules of thumb when it comes to good programming methods in relation to when to use what?
Yes, I strongly recommend to read Framework Design guidelines for best practices of good programming.
Properties are the preferred way to cover fields to enforce encapsulation. However, they are functional in that you can expose a property that is of a different type and marshal the casting; you can change access modifiers; they are used in WinForms data binding; they allow you to embed lightweight per-property logic such as change notifications; etc.
When looking at other peoples code, properties have different intellisense icons to methods.
If you think properties are just extra code, I would argue sticking with them anyway but make your life easier by auto-generating the property from the field (right-click -> Refactor -> Encapsulate Field...)
Properties allow you to do things other than set or get a value when you use them. Most notably, they allow you to do validation logic.
A Best Practice is to make anything exposed to the public a Property. That way, if you change the set/get logic at a later time, you only have to recompile your class, not every class linked against it.
One caveat is that things like "Threading.Interlocked.Increment" can work with fields, but cannot work with properties. If two threads simultaneously call Threading.Interlocked.Increment on SomeObject.LongIntegerField, the value will get increased by two even if there is no other locking. By contrast, if two threads simultaneously call Threading.Interlocked.Increment on SomeObject.LongIntegerProperty, the value of that property might get incremented by two, or by one, or by -4,294,967,295, or who knows what other values (the property could be written to use locking prevent values other than one or two in that scenario, but it could not be written to ensure the correct increment by two).
I was going to say Properties (setters) are a great place to raise events like NotifyPropertyChanged, but someone else beat me to it.
Another good reason to consider Properties: let's say you use a factory to construct some object that has a default constructor, and you prepare the object via its Properties.
new foo(){Prop1 = "bar", Prop2 = 33, ...};
But if outside users new up your object, maybe there are some properties that you want them to see as read-only and not be able to set (only the factory should be able to set them)? You can make the setters internal - this only works, of course, if the object's class is in the same assembly as the factory.
There are other ways to achieve this goal but using Properties and varying accessor visibility is a good one to consider if you're doing interface-based development, or if you expose libraries to others, etc.

C#: Can someone explain the practicalities of reflection? [duplicate]

This question already has answers here:
When do you use reflection? Patterns/anti-patterns
(17 answers)
Closed 9 years ago.
So I tried searching SO hoping someone had a good explanation of this, with no luck.
I asked another friend of mine a different question (which I've now forgotten) and his answer was simply "reflection" before he signed off.
I am still very new to the C# world, having been an amateur VB.net programmer (also JavaScript, ActionScript, and C), and am trying as hard as I can to grasp these advanced concepts.
There's lots of philosophical answers -- "application looking at itself" -- but they don't provide any practical hints on what is actually going on or how it is used within that context.
So, what is reflection, why is it important, and why/how do I use it?
Reflection provides the ability to determine things and execute code at runtime.
You don't have to use it if you don't want to, but it is extremely handy for dynamic behavior.
For example:
a) You can use reflection to configure your application by loading an external configuration file and starting services based on it. Your application wont have to know in advance about the classes that implement those services, as long as they conform to a specific interface or API.
b) Using reflection you can generate classes and code on the fly, which simplifies certain programming tasks since the programmer does not have to explicitly create all the needed code.
c) Reflection is also invaluable for programs that work by examining code. An example of that would be an IDE or a UI designer.
d) Reflection helps you reduce boilerplate code.
e) Reflection is handy for defining mini Domain Specific Languages (DSL) in your code.
(my defintion)
Reflection is the ability to write static code that executes code at run-time, that is normally determined at compile time.
For instance, I could call a class method to draw by compiling in that command eg:
pen.DrawLine()
or With reflection, I can first see if my object has a method called "drawline" and if so, call it. (Note this isn't the actual C# Reflection syntax)
if(pen.Methods.Contains("DrawLine"))
{
pen.InvokeMethod("DrawLine"))
}
I'm no reflection master, but I used reflection for a plug-in architecture.
With reflection I can load a .NET assembly (a dll in this case) at run time, find out all the types that are in the .NET Assembly, see if any of those types implement a specific interface, and if so, instantiate the class, to which I invoke the interface methods.
I know that use-case is a bit technical, but essentially reflection allows me to load plug-ins dynamically (ie at run-time), and lets me make type-safe calls to it.
The most common use of reflection is an extension of what used to be called RTTI (run-time type information) and was primarily the domain of C++ programmers.
Reflection is a side-effect of the way .net is built and that Microsoft elected to expose the libraries they used to create Visual Studio and the .net run-time to developers outside of Microsoft.
Most of the reflection library focuses on type discovery and creation that can be invoked at run-time. This allows for some very powerful self-referential code. Take the following example at the heart of our configuration management system (some bits deleted for clarity):
public static IMyCompanySetting UnwrapSetting(XmlNode settingNode)
{
string typeName = settingNode.Attributes["type"].Value;
string typeAssembly;
if(settingNode.Attributes["assembly"] != null)
{
typeAssembly = settingNode.Attributes["assembly"].Value;
}
Type settingType = null;
Assembly settingAssembly = null;
try
{
// Create an object based on the type and assembly properties stored in the XML
try
{
settingAssembly = Assembly.Load(typeAssembly);
if (settingAssembly == null)
{
return null;
}
}
catch (Exception outerEx)
{
try
{
settingType = GetOrphanType(typeName);
}
catch (Exception innerEx)
{
throw new Exception("Failed to create object " + typeName + " :: " + innerEx.ToString(), outerEx);
}
}
// We will try in order:
// 1. Get the type from the named assembly.
// 2. Get the type using its fully-qualified name.
// 3. Do a deep search for the most basic name of the class.
if (settingType == null && settingAssembly != null) settingType = settingAssembly.GetType(typeName);
if (settingType == null) settingType = Type.GetType(typeName);
if (settingType == null) settingType = GetOrphanType(typeName);
if (settingType == null) throw new System.Exception(
String.Format("Unable to load definition for type {0} using loosest possible binding.", typeName));
}
catch (Exception ex)
{
throw new CometConfigurationException(
String.Format("Could not create object of type {0} from assembly {1}", typeName, typeAssembly), ex);
}
bool settingIsCreated = false;
IMyCompanySetting theSetting = null;
// If the class has a constructor that accepts a single parameter that is an XML node,
// call that constructor.
foreach (ConstructorInfo ctor in settingType.GetConstructors())
{
ParameterInfo[] parameters = ctor.GetParameters();
if (parameters.Length == 1)
{
if (parameters[0].ParameterType == typeof(XmlNode))
{
object[] theParams = { settingNode };
try
{
theSetting = (IMyCompanySetting)ctor.Invoke(theParams);
settingIsCreated = true;
}
catch (System.Exception ex)
{
// If there is a pre-existing constructor that accepts an XML node
// with a different schema from the one provided here, it will fail
// and we'll go to the default constructor.
UtilitiesAndConstants.ReportExceptionToCommonLog(ex);
settingIsCreated = false;
}
}
}
}
This code allows us to create a limitless number of classes that implement IMyCompanySetting and serialize and deserialize themselves using XML. Then, given a chunk of XML that is the output of object serialization, the system can turn it back into an object, even if the object itself is from a library that the serialization library doesn't have staticly linked.
There are 3 things that reflect does here that would be impossible without it:
Load an assembly at run-time based on its name.
Load an object from an assembly at run-time, based on its name.
Call an object constructor based on signature for an object of a class that is not known at compile time.
Say you have two alternate implementations of an interface. You want to allow the user to pick one or the other, via a simple text config file.
With reflection, you can simply read the name of the class whose implementation you want to use from the config file (as a string), and instantiate an instance of that class.
Reflection lets you dig into an assembly and use it, no matter that you don't have it referenced later.
Consider a plug-ins system, in which the host doesn't know about the plug-ins it will hold; with Reflection (and the correct architecture), you can construct a simple solution achieving this.
Consider another scenario in which you must to call the method on an object given a string, Reflection gives you the approach to achieve this as well.
There are many other usages but i hope these two, open your apetite to this excellent feature of CLR
It's sometimes useful to be able to read properties or invoke methods of a class without knowing what properties or methods a class has at design time. The way to accomplish this is with reflection. As demonstrated by the code below, you can get a list of all properties on a class and retrieve their values without knowing anything about it at compile time. Or you can get a method by name, even if you don't know the name of the method at compile time, and invoke it via reflection. This would allow you, for example, to create a scripting language that operates on objects defined in another user-supplied DLL. (Of course you can also enumerate all methods in a class or retrieve a specific property by name, but these cases are not demonstrated in the code below.)
class Program
{
static void Main(string[] args)
{
UserDefinedClass udc = new UserDefinedClass();
udc.UserProperty = "This is the property value";
ClassTracer ct = new ClassTracer(udc);
ct.TraceProperties();
ct.CallMethod("UserFunction", "parameter 1 value");
}
}
class ClassTracer
{
object target;
public ClassTracer(object target)
{
this.target = target;
}
public void TraceProperties()
{
// Get a list of all properties implemented by the class
System.Reflection.PropertyInfo[] pis = target.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in pis)
{
Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(target, null));
}
}
public void CallMethod(string MethodName, string arg1)
{
System.Reflection.MethodInfo mi = target.GetType().GetMethod(MethodName);
if (mi != null)
{
mi.Invoke(target, new object[] { arg1 });
}
}
}
class UserDefinedClass
{
private string userPropertyValue;
public string UserProperty
{
get
{
return userPropertyValue;
}
set
{
userPropertyValue = value;
}
}
public void UserFunction(string parameter)
{
Console.WriteLine("{0} - {1}", userPropertyValue, parameter);
}
}
Reflection is using the code to examine the code itself. For example, instead of calling foo.DoBar() you could call:
foo.GetType().GetMethod("DoBar").Invoke(foo,null);
That seems like a round-about method of getting to the same destination, but it can also be used to do some black magic that might break the rules, like calling private methods on framework classes, for example. It can also be used to actually generate code and output new binaries, and a whole slew of things that are extremely useful to a small group of people.
For more information, check out the MSDN section on Reflection.
There are many cases in which the application should not assume much about itself and should look at runtime to see what it actually is. This is where reflection comes into the show. For example, ASP.NET makes no assumption about the membership provider you use except that it inherits the appropriate class. It uses reflection to lookup the class at runtime and instantiate it. This gives out a great deal of extensibility due to decoupling and decreasing dependencies between classes.
This is, of course, only a single use case for reflection. There could be many other cases where it might be very useful.
Andrew Troelsen, author of Pro C# 2008 and the .NET 3.5 Platform, defines reflection this way:
In the .NET universe, reflection is the process of runtime type discovery.
I'm not sure I could give you an accurate explanation of what that means, but I can tell you how I've used it.
I can put a user-defined attribute on an assembly (dll). Using reflection at run-time, I can inspect all of the assemblies in a certain directory location to see if they have this attribute defined. This can clue my application on how to use the assembly, say as a plug-in.
I've also used reflection to load and save application settings.
For what it's worth, unless you're using reflection, I'm not sure what it has to do with your GUI throwing exceptions.
About the only thing I know about C#
reflection is that it is annoying as
hell because all my GUI apps like to
throw incredibly annoying, pointless
"Exception has been thrown by the
target of an invocation" exceptions at
Application.Run(new frmMain());,
instead of stopping where the real
problem happened (as shown in the
innerException).
Your statement makes me believe you have few if any try/catch blocks anywhere in your application such that every exception is percolating back to the top of the call stack. If you are using Visual Studio 2005/2008 in debug mode, go into the Debug menu and select the Exceptions... menu option. Inside the Exceptions dialog, check the checkboxes under the Thrown column. Now, when you run your application and an exception is thrown, the debugger will break where the exception is thrown.
Let's say you have some business entities which all come derive from a base class called Entity. Let's also say that you need/want all the derived classes to be cloneable. You can implement a method "Clone" (interface ICloneable) on the base class which would loop through all the properties of the current class (although it is implemented at the Entity class) and copy them to the cloned object. This is a case where Reflection can really help. Because you can't know the name and the count of the properties at the base class. And you don't want to implement the method in all derived classes. However you might want to make the method virtual.
Other people have answered for
what is reflection, why is it important
So I will be answering following questions only.
How do I use it?
Through following namespaces
System.Reflection
System.Reflection.Emit
Why do I use it?
To invoke/inspect assembly types, members, properties
When you look at a product like Reflector, being able to inspect code structure is more than practical enough.
If you run fast and furious, maybe you're inheriting from an object and need access to a private field. You don't have source, but thats ok you have Reflection. (hacky I know)
A more legitimate use I've seen is to use reflection in implementing C# generics where I want to do some operation on the generic type that isn't otherwise available. The only operations available on a generic type are those made available with a generic constraint (ie, if you constrain the generic type to implement IFoo, you can use IFoo methods on instances of that class). Some operations though just aren't available- for instance I was taking a generic class that was supposed to have a particular non-default constructor. I couldn't constrain the generic method to only accept generic type parameters with that constructor, but at least I could try and use that constructor when implementing the generic via reflection.
I use reflection sparingly but it occasionally comes in real handy.
I have used reflection to implement a custom data bindings system.
For example, with my bindings API I can write the following:
Binding b = new Binding(textBox, "Text", myObject, "Text", BindingMode.Bidirectional);
Any changes to the text in the textBox object are detected by the Binding object (which attaches to the TextChanged event) and passed into the myObject.Text property. Changes to myObject.Text are detected (by its TextChanged event) and passed into the textBox.Text member.
I implemented this system using reflection. The Binding constructor is declared as:
Binding(object, string, object, string, BindingMode)
The system therefore works with any object (with one important proviso).
I inspect the first object and find the member corresponding to the named member in the first string (textBox and "Text", ie. does textBox have a member called "Text"). Repeat with the second object and string.
Proviso: for objects to be used in this scheme they must implement the informal requirement that any bindable property must have a corresponding PropertyNameChanged event. Happily, pretty much all the .Net UI components follow this convention.
I then inspect the object for the requisite PropertyNameChanged events, add event handlers to them, and everything is set.
NB. I implemented this in .Net 1.0, so it predates Microsoft's bindings implementation - which I have not yet got round to investigating.
Practical Application
Use reflection for aligning Data with objects, as in a data mapping situation. For example, you can map a database column to an object's property. If you were to write an Object Relational Mapper, you would need some way to get from a configuration setting (i.e. DatabaseColumnName maps to Class.MemberName) to the objects to which it referring.
Reflection is so named because it allows ones code to take a look at itself just like looking in a mirror.
As previously mentioned reflection may be used to create new instances using a class name. Serialization is also powered by reflection. In this case the code examines all the serializable fields and serializes those recursively until the entire graph has been consumed and its byte form written.
Reflection allows one to escape static typing at compile time by discovering types, methods, fields etc at runtime. Many dynamic languages on the JVM (not sure about CLR but id imagine the same is true) use reflection to dispatch methods.
In terms of a practical use for reflection we have used it to allow our customers to provide their own localisation.
With our applications we provide a local resource database that the client can work through providing language translation for all strings, menu items, dialog controls...etc. With this client translated database in place we then use reflection on application launch and iterate through all our controls and replace default language strings with the client supplied translated strings.
There are many uses for reflection that have already been detailed here but another use might be to log the state of an object including its private members for use in debugging.
Can you post some sample code which shows how you are performing reflection? Do you have the PDB files in the same location as the assembly on which you are using the reflection API's?
If so, then in Visual studio go to the Debug menu -->Exceptions and check the check box "Common Language runtime thrown". Run your application in debug mode. Hopefully the debugger should break at the point in your reflected assembly at which the real exception is being thrown.

Design time serialization in C#

I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form.
The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing.
In the resx file for the form it will generate binary data for storing the collection, however any time I make a change to the serialized class I get designer errors and need to delete the data manually out of the resx file and then recreate this data.
I have tried changing the constuctor to have a try / catch block around each property in the class
try
{
_Name = info.GetString("Name");
}
catch (SerializationException)
{
this._Name = string.Empty;
}
but it still crashes. The last error I got was that I had to implement IConvertible.
I would prefer to use xml serialization because I can at least see it, is this possible
for use by the designer?
Is there a way to make the serialization more stable and less resistant to changes?
Edit:
More information...better description maybe
I have a class which inherits from Component, it has one property which is a collection of Rules. The RulesCollection seems to have to be marked as Serializable, otherwise it does not retain its members.
The Rules class is also a Component with the attribute DesignTimeVisible(false) to stop it showing in the component tray, this clas is not marked Serializable.
Having the collection marked as Serializable generates binary data in the resx file (not ideal) and the IDE reports that the Rules class is not Serializable.
I think this issue is getting beyond a simple question. So I will probably close it shortly.
If anyone has any links to something similar that would help a lot.
You might want to try the alternate approach of getting everything to serialize as generated code. To do that is very easy. Just implement your non-visual class from Component. Then expose your collection as you already are but ensure each object placed into the collection is itself derived from Component. By doing that everything is code generated.
I have since discovered where I was going wrong.
The component I was implementing a custom collection (inherited from CollectionBase), I changed this to a List and added the DesignerSerializationVisibility(DesignerSerializationVisibility.Content) attribute to the List property, this list is also read-only. This would then produce code to generate all the components properties and all the entries in the List.
The class stored in the list did not need any particuar attributes or need to be serializble.
private List<Rule> _Rules;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public List<Rule> Rules
{
get { return _Rules; }
}
Could you put more code up of the class that is having the serialization issue, maybe the constructor and the property to give reference to the variables you're using.
Just a note:
I've had a lot of issues with the visual designer and code generation, if I've got a property on a control then generally I put
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
on the property and handle the initialization myself.

Categories