Object does not match target type in DesignData - visual-studio-2010

I'm throwing this out in case someone has encountered this before.
When creating DesignData for use within the WPF designer, I get one of two errors:
Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object
target)
(SNIP)
at Microsoft.Expression.DesignModel.InstanceBuilders.ClrObjectInstanceBuilder. UpdateProperty(IInstanceBuilderContext
context, ViewNode viewNode, IProperty
propertyKey, DocumentNode valueNode)
The other one is a little more informative:
The value "_.di0.MyProjectLol.MyType"
is not of type "MyProjectLol.MyType"
and cannot be used in this generic
collection.
at
System.ThrowHelper.ThrowWrongValueTypeArgumentException(Object
value, Type targetType)
(SNIP)
at Microsoft.Expression.DesignModel.InstanceBuilders.ClrObjectInstanceBuilder.
InstantiateChildren(IInstanceBuilderContext
context, ViewNode viewNode,
DocumentCompositeNode compositeNode,
Boolean isNewInstance)
When debugging, I can see that there is a dynamic assembly that is loaded with proxy-ish types that look like mine but, obviously, are not. This assembly is called Blend_RuntimeGeneratedTypeAssembly(Guid goes here). When attempting to load types in this assembly, it throws a type load exception for a number of them. So, some types get proxied, some types are left as God and I intended, and when they mix unnatural acts occur.
For example, the type "Foo" might get a proxy created, but no other types do (TypeLoadExceptions). Then the designer tries to hand one of my real types the proxy (helped by the fact that xaml serialization likes to cast collections to IList, thus shitting on type safety) and you get one of the above exceptions.
I have spent half a week trying to fix this. I've tried a hundred different things, but I can't figure out exactly what is causing it to fail. Suggestions are welcome, TIA.

Solution in two parts:
1) Ensure VS is fully updated. At this point, it means installing the Silverlight 4 tools for Visual Studio 2010. They include the latest updates to the WPF designer. If you're reading this off in the distant future, ignore this one.
2) Hit the properties for your design data files. Clear out "Custom Tool", and set the "Build Action" to either "DesignData" or "DesignTimeDataWithDesignTimeCreatableTypes".
DesignData means that your types cannot be deserialized from xaml directly (due to dependencies or the such), so the designer attempts to create mocks for those types and presents the mocks to your design surface.
DesignTimeDataWithDesignTimeCreatableTypes means that the designer will load your assemblies and deserialize the xaml directly into your types without creating mocks.

This can also be caused by a certain combination of situations that, when combined, cause deserialization to fail.
Essentially if you have
A custom collection, or a collection that doesn't implement IList
That is exposed as a property on your type
Which is defined in a different assembly
you can get this error message as well.
It is very important that your collection property types implement IList (the non-generic one) if you want to serialize them to and from xaml!

Related

How to use IProjectionBuffer in MEF without creating editor instance?

I am trying to create a Visual Studio extension which handles a multi-language content type. Much like some mvc-templates and Django or ASP.NET which a certain part of the code is in another language.
I know that I should use Projection and I already checked Django for Visual Studio extension but the solution there includes creating a Language Service and going to the trouble of creating all bits and pieces related to a code editor. Here I am trying to achieve the same goal just by using MEF.
I know that you can use IProjectionBuffer CreateProjectionBuffer() to create a projection but the question is how to replace the current TextBuffer with the created one and when is the best time to do it.
Also one may expect that if he specifies a base definition of type "projection" like this:
[Export]
[Name("Whatever")]
[BaseDefinition("code")]
[BaseDefinition("projection")]
internal static ContentTypeDefinition WhateverContentType = null;
the received TextBuffer in providers to be of type IProjectionBuffer (after all IProjectionBuffer is inherited from ITextBuffer). Which are not and it seems that a projection base definition has no effect what so ever.
So if I want to rephrase my question in a tldr version:
How and when do you apply an IProjectionBuffer to current view (using MEF and without creating an editor instance)?
So if I understand your question correctly, the answer is "you don't." A IWpfTextView is bound to a implementation of ITextBuffer (or a derived type, like IProjectionBuffer) at creation time, and can't be changed. Even if you could, many other extensions and language services would be most surprised by this and would probably crash.
To address your second question about content types: simply declaring you have a base content type of "projection" doesn't make you a projection buffer. All that really states is you might be creating projection buffers of that type, and when you do you want some extra ITagger support so taggers project through to the source buffers as you might expect them to.

GetExportedTypes() on an assembly throws NotSupportedException

I'm having some serious troubles getting a Windows Phone 7.5 class library to load into the WP Unit Test Framework. It internally calls GetExportedTypes() on my assembly which throws a ReflectionTypeLoadException that doesn't contain any details. Its message is "ReflectionTypeLoadException" and its LoaderExceptions is null ("Could not evaluate expression"). The assembly is not using any 3rd party assemblies. If I create a separate WP7 app and do the same thing, I get the same results. I'm a very experienced Reflection user, but the lack of any detailed errors has brought my research to a complete halt. Just for completeness, it's the Windows Phone version of Fluent Assertions.
What about the Types array on the exception? Does it contain values? If so, does it also contain nulls? If so, you can find out which classes failed to load: You know all classes in the assembly and you know which classes loaded correctly. Those that are missing are the classes that couldn't be loaded. Maybe this info gives some clues.
This answer is based on the documentation, especially these bits:
From the Remarks of the LoaderExceptions property:
The LoaderExceptions property retrieves an array of type Exception that is parallel to the Types array. This array will contain null values whenever reflection cannot load a class.
And from the documentation of the Types property:
An array of type Type containing the classes that were defined in the module and loaded. This array can contain some null values.
I've found it! #GeertvanHorrik pointed me at a blog post he recently wrote. I was using an covariant interface (using the out parameter) which the runtime (!) doesn't support. Why the compiler does not protect me from that is a big mystery (and a huge disappointment) to me

Registering all types in Assembly for Unity

I'm working on a large Asp.Net MVC3 application (>50 views) and we are currently planning on using Unity for our dependency injection framework. For ease of maintenance, I would like to be able to query the assembly to find all of the base types, then register them with Unity.
Based on sample code from the Unity MVC3 Project for registering all controllers, I tried the following code -
var orchestratorTypes = (from t in Assembly.GetCallingAssembly().GetTypes()
where typeof(IOrchesratorBase).IsAssignableFrom(t) &&
!t.IsAbstract
select t).ToList();
orchestratorTypes.ForEach(t => container.RegisterType(t);
When I run the application I get the following error message
The current type, WwpMvcHelpers.BaseClasses.IOrchesratorBase, is an interface and cannot be constructed. Are you missing a type mapping?
If I register the class using individually, as below -
container.RegisterType<IOrchesratorBase, HomeOrchestrator>();
Everything works correctly. Is there a way to do this so that I don't have to register each type individually?
EDIT
Per request, my inheritance hierarchy is
HomeOrcestrator <- IOrchesratorBaseList<LocalModel>
<- OrchesratorBase<LocalModel> <- IOrchesratorBase
The usage in the controller is
public class HomeController : ControllerListBase <HomeOrchestrator, LocalModel>
{
public HomeController() {}
public HomeController(IOrchesratorBase homeOrchestrator) {
this.Orchestrator = (HomeOrchestrator) homeOrchestrator;
}
The LINQ to get the types appears to work. I don't think that's your problem.
You'll get a similar error if you just write
container.RegisterType(typeof(HomeOrchestrator));
and call container.Resolve<IOrchesratorBase>().
In other words, RegisterType(t) is not the same as RegisterType<I, T>().
The real question is, what are you resolving and how do you want it resolved? Your query is finding implementors of IOrchesratorBase. Are your injection constructor parameters of that type? If so, what's Unity supposed to do when 20 types implement that interface?
Can you provide more information on your class/interface hierarchy, constructor parameters, and what you expect/want to happen?
(I'd refactor to change IOrchesratorBase to IOrchestratorBase, BTW.) :)
Edit
Based on the edited question, the problem is that, in order to resolve a HomeController, Unity is looking for a type registration for IOrchesratorBase. It determines the interface type by the parameter types of the constructor with the most parameters.
If you write container.RegisterType<IOrchesratorBase, HomeOrchestrator>() the answer is obvious - Unity will construct an instance of HomeOrchestrator and inject it.
Now, is there more than one type that implements IOrchesratorBase? If so, and you register both of them (explicitly), Unity will use whichever one you register last. That may not be what you want.
If you have multiple controllers, each taking a different interface type in their constructors (with only one implementation per interface), you'll need to figure out what each interface type is and re-run your LINQ registration for each one. That could be done via reflection - find the orchestrators or the controllers.
If you have multiple controllers, each taking the same interface type in their constructors and you want different implementations for each, you've got a problem. You'd have to register named types and determine the names somehow, or something similar.
Unity isn't magic. It can't figure out your intentions.
Addendum
Unity can operate in a convention-over-configuration mode; see Using Unity With Minimal Configuration.

VS2010 Class Diagram - How to show collection associations between two interfaces?

I'm generating some class diagrams from existing code to improve the documentation but I've run into a bit of an obstacle. I'd like to show collection associations on the diagram, but for interfaces this just doesn't seem possible.
If the interfaces are in another assembly, the collection type is displayed in its unbounded form (e.g. ReadOnlyObservableCollection1`) and attempting to display collection associations gives the error
This is not a valid type name.
If the interfaces are in the same assembly, the collection type is displayed in its bounded form (e.g. ReadOnlyObservableCollection`), but attempts to display the associations come out with the error message
Cannot show an association because cannot be found.
Any ideas what I'm doing wrong, or is this just a shortcoming of VS class diagrams?
Thanks,
James
I found that by removing and removing and re-adding the reference of the assemble containing the offending class, solved the issue.

InvalidDataContractException in windows phone 7?

I am developing an app where i am navigating from different pages Particularly in one page when i am pressing the windows(start) button to come out of the app it is throwing the following exception and Message:
System.Runtime.Serialization.InvalidDataContractException:
Type 'System.Windows.SetterBase' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.
But i am not getting why this error is occurred. Any suggestions??
I would guess that when you are naivgating from that page you are either serializing something or saving something in IsolatedStorageSettings. This uses the DataContractSerializer internally to convert objects into something that can be persisted.
Either make sure that the object can be serialized or serialize it yourself. If you can do it yourself using a different/faster method you may be able to improve performance overall. The DataContractSerializer is quite fast with simple types like strings.

Resources