WinRT Reflection (C++/CX) - reflection

how can I introspect an object in C++/CX? I known how to get its class name (using IInspectable) but I wasn't able to figure out how to get a list of its properties or how to invoke methods if I have just a name of the method (string). I searched for an answer here and at Google but what I found is related to the .NET layer of WinRT (the System.Reflection namespace doesn't seem to be available in C++/CX).

As hinted by svick, you take the class name (retrieved from IInspectable::GetRuntimeClassName), hand it to RoGetMetaDataFile. This returns an IMetaDataImport2. Now call IMetaDataImport2::FindTypeDefByName. This returns a typedef token. Now call IMetaDataImport2::GetTypeDefProps which will give you properties about the type.
From the typedef properties, you can retrieve other information - enumerate the methods/fields if it's an interface/struct (or enum), find the type of the runtime class (if it's an interface or a class), etc.

C++ doesn't provide any specific APIs to reflect on WinRT types, these types are fully defined in CX compliant metadata files and you can use the CLR native metadata APIs to read their definition. There is a snippet at
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/211ef583-db11-4e55-926b-6d9ab53dbdb4/ccx-reflection
James McNellis released a full C++ library for CX reflection last year
http://seaplusplus.com/2012/04/26/cxxreflect-native-reflection-for-the-windows-runtime/

Even most of the normal .Net reflection isn't included in the subset of .Net available to WinRT applications. And I didn't find any reflection-related types in the WinRT documentation. This means that (unless I overlooked something) reflection is simply not exposed by the available APIs.
Although I don't see why it shouldn't be available. The metadata is there, which should be enough.
When looking at the C++-specific functions, there is the function RoGetMetaDataFile(). It seems it should be possible to use it to get the metadata. But it's a native C++ function, not C++/CX. This means it's not easy to use (manual memory management, …) and I doubt it will be allowed in apps that are in the Store.

Related

How Json.Net/NewtonsoftJson decides on how to serialize/deserialize depending on platform AOT or JIT

I'm profiling newtonsoft json inside unity, on my android device with 2 different scripting backend, Mono which supports IL Emit or in another words, code generation. But also IL2CPP, which does not support code generation.
What Im benchmarking is, serialization and deserialization of a simple reference type with a single public field.
With properties (not fields) I know that we could take advantage of Delegate.CreateDelegate (event in AOT platfoorms) giving the PropertyInfo, but the same is not true for fields, since there are no GetterMethod or SetterMethod.
So, what Im thinking is that Newtonsoft json was taking a look on which platform is running, so for example, if platform supports IL Emit, then, emit a getter and setter for the field, if not, fallback to reflection, but I got the same results on my android benchmark for Mono and IL2CPP.
So I would like to understand why I got the same result, reflection is not only being used as fallback? Thanks in advance!

How to does WindowsRT Data-binding do type conversion without TypeConverterAttribute

In a previous question/answer I learnt how data-binding in Windows Phone does TypeConversion for string to ImageSource using the TypeConverterAttribute - see https://stackoverflow.com/a/16753488/373321
I'm now looking at the same problem in WindowsStore apps where TypeConverterAttribute doesn't exist.
If I use WinRT data-binding then clearly the data-binding layer still manages to do the correct conversion. The MSDN documentation says:
this behavior relies on underlying type conversion that processes the string as a URI, and calls the equivalent of the BitmapImage(Uri) constructor.
However, I can't see any meta-data anywhere about how it knows what conversion to do.
I'm trying to build my own data-binding implementation - so being able to mimic what WinRT does would be very useful.
Is there a queryable metadata hint somewhere which tells the Xaml data-binding what conversion to apply? Or is this string to ImageSource conversion somehow baked into the run-time, hidden from the CLR layer?
If it is hidden, is there a list anywhere of known automatic type conversions so that I could cache them in my data-binding implementation?
I discussed this question via Twitter with one of the WinRT devs (Tim Heuer)
A basic summary of this conversation was:
WinRT does not have anything like TypeConverterAttribute
A small number of WinRT controls do have a small number of internal conversions that they will apply
There is no information publicly available about which controls and conversions these are
In Windows 8 Apps, this is generally handled by creating a class that inherits from IValueConverter, and is then assigned alongside the particular data binding. As stated on the msdn site:
"Create a converter by implementing the IValueConverter interface and implementing the Convert method. That method should return an object that is of the same type as the dependency property that the binding targets, or at least a type that can be implicitly coerced or converted to the target type."
Here is the link to the full doc: http://msdn.microsoft.com/en-US/library/windows/apps/windows.ui.xaml.data.binding.converter.aspx
See the "Examples" section for further detail.
To answer your question, there is no metadata hint, you simply create your converter and then explicitly assign the converter alongside your custom data binding.

Determining type of CollectionBase via Reflections (or Microsoft.Cci)

Question:
Is there a static way to reliably determine the type contained by a type derived from CollectionBase, using Reflection or Microsoft.Cci?
Background:
I am working on a code generator that copies types, makes customized versions of those types, and converters between. It walks the types in the source assembly via Microsoft.Cci. It prints out source code using textual templates. It does a lot of conversion and customization, and tosses out code that I don't care about.
In my resulting code, I intend to replace List<T> everywhere that a CollectionBase, IEnumerable<T>, or T[] was previously used. I want to use List<T> because I am pretty sure I can serialize it without extra work, which is important for my application. T is concrete in every case. I am trying not to copy CollectionBase classes because I'd have to copy over the custom implementation, and I'd like to avoid having to do that in my code generator.
The only part I'm having a problem with is determining T for List<T> when replacing a custom CollectionBase.
What I've done so far:
I have briefly looked at the MSDN docs and samples for CollectionBase, and they mention creating a custom Add method on your derived type. I don't think this is in any way enforced, so I'm not sure I can rely on that. An implementor could name it something else, or worse, have a collection that supports multiple types, with Object as their only common ancestor.
Alternatives I have considered:
Maybe the default serialization does some tricks that I can take advantage of. Is there a default serialization for CollectionBase collections, or do you generally have to implement it yourself? If you have to do it yourself, is there some reliable metadata I could look at in order to determine the types? If it supports default serialization, does it rely on the runtime types of the items in the collection?
I could make a mapping in my code generator of known CollectionBase types, mapped to their corresponding T for List<T>. If a given CollectionBase type that I encounter isn't in the list, throw an exception. This is probably what I'll go with if I there isn't a reliable alternative.
I'm still not sure enough about what you want to do to give advice. Still, do your CollectionBase-derived classes all implement Add(T)? If so, you could look for an Add method with single parameter of type other than object, and use that type for T.

Flex - XML Serialization and De-Serialization of nested Object structures

Our Flex app would like to work with requests and responses as object graphs (nothing unusual there) e.g. response becomes the model of some view, and would be a structure with several layers of nesting.
** Now, ideally we would like to use the same client (and server) side objects for different message formats e.g. XML and AMF, and have a pluggable serialization/de-serialization layer (!)
AMF has serialization and matching of client to server using
[RemoteClass(alias="samples.contact.Contact")]
but it seems there is no equivalent for XML.
I am (somewhat optimistically) looking for a neat way of serializing the object graph to XML, to send through a HTTPService from the client.
For responses, the default 'object' and 'E4X' provide some de-serialization. This is handy, but of course we don't have the niceties of unpacking the XML back into specific AS classes like we do with AMF.
Any suggestions?
(did have one idea come through about wrapping/casting object as XML or XMLList - this does not seem to work, however)
Update:
Both these libraries look useful, and I will very likely use them at some point.
For now, I really need the simplicity of re-using the metadata set for the AMF3 serialization which we are using in any case ([RemoteClass],[Transient])
.. so the best option at the moment is AMFX - used Flex Data Services for AMF transfer using XML - classes in mx.messaging.channels.amfx package - only drawback at the moment is any Externalizable class is transformed into a Hex byte stream - and ArrayCollection is Externalizable! (hoping to workaround by serializing the internal Array in a subclass ..)
Hope that's useful to someone ..
Regarding the Xml serialization I can give you a starting point (as biased as it may be, though :D).
I am working on a project that allows for automatic conversion of AS3 objects to and from xml. It basically uses annotations on the model objects you use for communication in order to construct the xml structure or populating an object from xml.
It is called FlexXB and you can check it out at http://code.google.com/p/flexxb/.
I started this project cos I got into the same issues at work (namely I have a server that communicates through xml) and I hoped it be of use to someone else.
Cheers,
Alex
Yet another project: FleXMLer (http://code.google.com/p/flexmler/).
It has both the straightforward attitude of asx3m where you can just call:
new FleXMLer().serialize(obj);
Or you can customize XML element names, skip elements and tweak the way arrays and hash tables are serialized.
Would appreciate your input.
checkout asx3m project at http://code.google.com/p/asx3m
It's an AS3 port of Java XStream serialization library and works pretty well.
I made it because I had to connect to a server platform that used XStream for exchanging data objects and put a lot of work in it.
It can be extended to serialize AS3 objects to any format (JSON for example) and could leverage power of user defined metatags.
Cheers,
Tomislav
There's a library including JSON available from Adobe, too. And since ActionScript is a superset of JavaScript ... and JSON is increasingly supported cross-framework ...

What is Reflection?

I am VERY new to ASP.NET. I come from a VB6 / ASP (classic) / SQL Server 2000 background. I am reading a lot about Visual Studio 2008 (have installed it and am poking around). I have read about "reflection" and would like someone to explain, as best as you can to an older developer of the technologies I've written above, what exactly Reflection is and why I would use it... I am having trouble getting my head around that. Thanks!
Reflection is how you can explore the internals of different Types, without normally having access (ie. private, protected, etc members).
It's also used to dynamically load DLL's and get access to types and methods defined in them without statically compiling them into your project.
In a nutshell: Reflection is your toolkit for peeking under the hood of a piece of code.
As to why you would use it, it's generally only used in complex situations, or code analysis. The other common use is for loading precompiled plugins into your project.
Reflection lets you programmatically load an assembly, get a list of all the types in an assembly, get a list of all the properties and methods in these types, etc.
As an example:
myobject.GetType().GetProperty("MyProperty").SetValue(myobject, "wicked!", null)
It allows the internals of an object to be reflected to the outside world (code that is using said objects).
A practical use in statically typed languages like C# (and Java) is to allow invocation of methods/members at runtime via a string (eg the name of the method - perhaps you don't know the name of the method you will use at compile time).
In the context of dynamic languages I haven't heard the term as much (as generally you don't worry about the above), other then perhaps to iterate through a list of methods/members etc...
Reflection is .Net's means to manipulate or extract information of an assembly, class or method at run time. For example, you can create a class at runtime, including it's methods. As stated by monoxide, reflection is used to dynamically load assembly as plugins, or in advance cases, it is used to create .Net compiler targeting .Net, like IronPython.
Updated: You may refer to the topic on metaprogramming and its related topics for more details.
When you build any assembly in .NET (ASP.NET, Windows Forms, Command line, class library etc), a number of meta-data "definition tables" are also created within the assembly storing information about methods, fields and types corresponding to the types, fields and methods you wrote in your code.
The classes in System.Reflection namespace in .NET allow you to enumerate and interate over these tables, providing an "object model" for you to query and access items in these tables.
One common use of Reflection is providing extensibility (plug-ins) to your application. For example, Reflection allows you to load an assembly dynamically from a file path, query its types for a specific useful type (such as an Interface your application can call) and then actually invoke a method on this external assembly.
Custom Attributes also go hand in hand with reflection. For example the NUnit unit testing framework allows you to indicate a testing class and test methods by adding [Test] {TestFixture] attributes to your own code.
However then the NUnit test runner must use Reflection to load your assembly, search for all occurrences of methods that have the test attribute and then actually call your test.
This is simplifying it a lot, however it gives you a good practical example of where Reflection is essential.
Reflection certainly is powerful, however be ware that it allows you to completely disregard the fundamental concept of access modifiers (encapsulation) in object oriented programming.
For example you can easily use it to retrieve a list of Private methods in a class and actually call them. For this reason you need to think carefully about how and where you use it to avoid bypassing encapsulation and very tightly coupling (bad) code.
Reflection is the process of inspecting the metadata of an application. In other words,When reading attributes, you’ve already looked at some of the functionality that reflection
offers. Reflection enables an application to collect information about itself and act on this in-
formation. Reflection is slower than normally executing static code. It can, however, give you
a flexibility that static code can’t provide

Resources