How can a custom markup extension for a graph of custom types loaded through XAML obtain a reference to the root object - xaml

I am attempting to write a MarkupExtension to support the process of instantiating custom types via XAML. My custom types are POCOs and not descendants of DependencyObject. There seems to be no straightforward XAML mechanism for MarkupExtensions to obtain references to objects in the graph that is being loaded. I note that the WPF machinery provides some of these capabilities but the relevant properties are all internal.
Any ideas?

I wrote a class that I use to bind to ViewModel commands, and it contains some code to retrieve the root of the XAML. It uses reflection on private WPF members, so it's not exactly clean, but it works... You can find it here
http://www.thomaslevesque.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/
BTW, it doesn't work with WPF 4 because the private implementation has changed... If you're interested I can post an updated version that takes these changes into account

Related

Adding new members and extending methods in an external API interface

I am building an VB.NET application in Visual Studio using SOLIDWORKS API - my application connects to SOLIDWORKS application via COM, and performs some actions in it using various API calls. The API is accessed by adding project references to SOLIDWORKS .dll files. These files must be embedded to the executable of my application for legal reasons.
This question is not specific to that API, but I will try to explain what I want to do. There is a SOLIDWORKS API interface called Body2 that governs manipulation of model objects (bodies) in 3D space. For example, Body2 interface provides a method ApplyTransform that allows moving or rotating a certain body by applying a MathTransform (a transform matrix) to it:
ModelBody.ApplyTransform(rotationMatrix) 'rotates the body
Now, the Body2 objects do not store these transformation matrices - they are applied and forgotten. However, in my application, I need to persistently store that information, so that at some point, I can reverse all transformations, and return the body to it's original position.
Therefore, I want to extend the Body2 interface by adding a new property to it, called "CombinedTransformMatrix", so that every time I call ApplyTransform, I could also update the value of this property, for example:
ModelBody.ApplyTransform(rotationMatrix)
ModelBody.CombinedTransformMatrix.Multiply(rotationMatrix)
ModelBody.ApplyTransform(translationMatrix)
ModelBody.CombinedTransformMatrix.Multiply(translationMatrix)
And when I finally want to return the body to it's original position, I could call:
ModelBody.ApplyTransform(ModelBody.CombinedTransformMatrix.Inverse)
ModelBody.CombinedTransformMatrix = New MathTransform 'reset matrix
Ideally, it would be really nice to also extend the ApplyTransform method, so that it would update the CombinedTransformMatrix automatically, for example:
Overrides Function ApplyTransform(Xform As MathTransform) As Boolean
'Do whatever SOLIDWORKS does in this function
'My additional code:
Me.CombinedTransformMatrix.Multiply(Xform)
End function
(I know I should do an extension rather than an override, but I don't know how)
If this is possible, then I could simplify the code for the body transformations, as the CombinedTransformMatrix would update automatically:
'Rotate and move
ModelBody.ApplyTransform(rotationMatrix)
ModelBody.ApplyTransform(translationMatrix)
'Return to original position
ModelBody.ApplyTransform(ModelBody.CombinedTransformMatrix.Inverse)
ModelBody.CombinedTransformMatrix = New MathTransform 'reset matrix
I would very much prefer this kind of a solution instead of creating some derived class from Body2, or making some kind of a wrapper class that stores CombinedTransformMatrix outside the Body2 object. I want to store that bit inside the object itself. As for derived class, Visual Studio doesn't even allow me to inherit from Body2 - says "'Body2Class' is not allowed when its assembly is configured to embed interop types.". And I must embed these .dll files because otherwise I would have to ship them along the .exe of my application, which is legally prohibited by SOLIDWORKS.
Is what I want possible? Can I add that CombinedTransformMatrix to the Body2 interface without creating a derived class? And is it possible to extend that ApplyTransform method with my additional code without knowing how that method is implemented?
If not, what is the next best solution to achieve what I want? Like I said, I would very much like to avoid wrappers or additional variables outside of Body2, because there will be lots of these Body2 objects, they will persist throughout the application's lifetime, each will have a different transformation, so having to store their transformation information outside themselves would seriously complicate my code.
There is no universal way of doing this. You can maintain the separate dictionary with your COM object (e.g. IBody2 in this case) to be a key and the additional parameters (tags) to be a value. You will need to manually update the dictionary to remove the data when the pointer is destroyed. There are however some specific SW interfaces that do have some ways to associate custom data (similar to tags). For instance, IBody2 has the IBody2::AddPropertyExtension2 which allows associating custom data with the body itself, IEntity has the IEntity::CreateStringAttributeDefinition (note, this is not documented method) etc.
But there is no something like universal System::Windows::Forms::Tag property for Windows Controls or Dependency Property for DependencyObjects exists for COM classes.

Custom XAML Applications (non-WPF and non-WWF)

This question is likely a particular XAML application. XAML is a custom markup to instantiate objects and, as such, define custom applications. Note that, it serves to both declare WPF user interfaces and WWF workflows. It would also help to specify, e.g., a custom source-code change detection solution. To avoid getting in deeper in unnecessary details. I need to design a custom XAML-based model that, like the one for WPF and the one for WWF do, allows me to declare a custom application on top of XAML, without having to create a WPF or WWF project. Is this sort of third-part XAML-like provider possible to build?
<Approach>
<PrimitiveExample
OriginalType={Type syntax:LiteralSyntax}
ModifiedType={Type syntax:LiteralSyntax}
Propagation.Matched={Binding MatchedPropagationCommand}>
...
</PrimitiveExample>
...
<Approach/>
Let us see it this way. Is there a way to get a stand-alone XAML file that works as follows?
a) There will be a project item, e.g., named "Stand-alone XAML".
b) I create a new "Stand-alone XAML" item named, e.g., "Solution.sccd", and I add it to a console application, class library, or many other projects. This because it will be a sort of smart .config.
c) I can set up a root instance in "Solution.sccd" (likely containing a lot of nested instances) - this is natural for XAML.
d) When declaring instances in "Solution.sccd", I can use features like attached properties, binding, and many other smart features or markup extensions that can be used with WPF or WWF, but this will not be a WPF or WWF project.
e) I can instantiate the declared root instance, e.g., with simple code line like "var rootObject = XAMLInstanceCreator.Create(Solution.sccd)", and use that object.
Does this make sense now?
Regards, Guillermo.

How to wire up WCF Service Application, Unity and AutoMapper

I have been playing around the last couple of days with different solutions for mapping DTO's to entities for a VS2013, EF6, WCF Service App project.
It is a fairly large project that is currently undergoing a major refactoring to bring the legacy code under test (as well as port the ORM from OpenAccess to EF6).
To be honest I had never used AutoMapper before but what I saw I really liked so I set out to test it out in a demo app and to be honest I am a bit ashamed that I have been unable to achieve a working solution after hours of tinkering and Googling. Here is a breakdown of the project:
WCF Service Application template based project (.svc file w/code behind).
Using Unity 3.x for my IoC container and thus creating my own ServiceHostFactory inheriting from UnityServiceHostFactory.
Using current AutoMapper nuget package.
DTO's and DAL are in two separate libraries as expected, both of which are referenced by the service app project.
My goal is simple (I think): Wire up and create all of my maps in my composition root and inject the necessary objects (using my DI container) into the class that has domain knowledge of the DTO's and a reference to my DAL library. Anyone that needs a transformation would therefore only need to reference the transformation library.
The problem: Well, there are a couple of them...
1) I cannot find a working example of AutoMapper in Unity anywhere. The code snippet that is referenced many times across the web for registering AutoMapper in Unity (see below) references a Configuration class that doesn't seem to exist anymore and I cannot find any documentation on its deprecation:
container.RegisterType<AutoMapper.Configuration, AutoMapper.Configuration>(new PerThreadLifetimeManager(), new InjectionConstructor(typeof(ITypeMapFactory),
AutoMapper.Mappers.MapperRegistry.AllMappers())).RegisterType<ITypeMapFactory,
TypeMapFactoy>().RegisterType<IConfiguration, AutoMapper.Configuration>().RegisterType<IConfigurationProvider,
AutoMapper.Configuration>().RegisterType<IMappingEngine, MappingEngine>();
2) Where to create the maps themselves... I would assuming that I could perform this operation right in my ServiceHostFactory but is that the correct place? There is a Bootstrapper project out there but I have not gone down that road (yet) and would like to avoid it if possible.
3) Other than the obviously necessary reference to AutoMapper in the DTO lib, what would I be injecting into the instantition, the configuration object (assuming IConfiguration or IConfigurationProvider) and which class I am injecting into the constructor of the WCF service to gain access to the necessary object.
I know #3 is a little vague but since I cannot get AutoMapper bound in my Unity container, I cannot test/trial/error to figure out the other issues.
Any pointers would be greatly appreciated.
UPDATE
So I now have a working solution that is testing correctly but would still like to get confirmation that I am following any established best practices.
First off, the Unity container registration for AutoMapper (as of 11/13/2013) v3.x looks like this:
container
.RegisterType<ConfigurationStore, ConfigurationStore>
(
new ContainerControlledLifetimeManager()
, new InjectionConstructor(typeof(ITypeMapFactory)
, MapperRegistry.AllMappers())
)
.RegisterType<IConfigurationProvider, ConfigurationStore>()
.RegisterType<IConfiguration, ConfigurationStore>()
.RegisterType<IMappingEngine, MappingEngine>()
.RegisterType<ITypeMapFactory, TypeMapFactory>();
Right after all of my container registrations, I created and am calling a RegisterMaps() method inside of ConfigureContainer(). I created a test mapping that does both an auto mapping for like named properties as well as a custom mapping. I did this in my demo app for two reasons primarily:
I don't yet know AutoMapper in a WCF app hosted in IIS and injected with Unity well enough to fully understand its behavior. I do not seem to have to inject any kind of configuration object into my library that does the transformations and I am still reading through the source to understand its implementation.
As I understand it, there is a caching mechanism at play here and that if a mapping is not found in cache that it will create it on the fly. While this is great in theory, the only way I could then test my mappings that were occurring in my composition root was to do some sort of custom mapping and then call Mapper.Map in the library that performs mapping and returns the DTO.
All of that blathering aside, here is what I was able to accomplish.
WCF Service App (composition root) injects all of the necessary objects including my DtoConversionMapper instance.
The project is made up of the WCF Service App (comp root), DtoLib, DalLib, ContractsLib (interfaces).
In my ServiceFactoryHost I am able to create mappings, including custom mappings (i.e. map unlike named properties between my DTO and EF 6 entity).
The DtoConversionMapper class lives in the DtoLib library and looks like this: IExampleDto GetExampleDto(ExampleEntity entity);
Any library with a reference to the DtoLib can convert back and forth, including the Service App where the vast majority of these calls will take place.
Any guiding advice would be greatly appreciated but I do have a working demo now that I can test things out with while I work through this large refactoring.
Final Update
I changed the demo project just a little by adding another library (MappingLib) and moved all of my DTO conversions and mappings to it in a static method. While I still call the static method in my composition root after the Unity container is initialized, this gives me the added flexibility of being able to call that same map creation method in my NUnit unit test libraries, effectively eliminating any duplication of code surrounding auto mapper and makes it very testable.

NServiceBus: need to configure channels for my Gateway with code

I'm engaged in building NServiceBus Gateway handler, and I need to avoid config files so that all configuration is defined inside c# classes. As a result I have to convert the following section to c# code
<GatewayConfig>
<Channels>
<Channel Address="http://localhost:25899/SiteB/" ChannelType="Http" Default="true"/>
</Channels>
</GatewayConfig>
I've found GatewayConfig, ChannelCollection and ChannelConfig in a NServiceBus.Config namespace, but I can not link them together, coz GatewayConfig refers to ChannelCollection, but ChannelCollection has nothing to do with ChannelConfig. Please help
Just create a class implementing IProvideConfiguration of GatewayConfig. That gives you a way to provide your own config. Look at the pubsub sample for the exact details on how to do this.
Well, I've found the way to do it as I installed Reflector and looked into the implementation. There is a ChannelCollection.CreateNewElement() method returning back System.Configuration.ConfigurationElement. NServiceBus overriden the method instantiating ChannelConfig inside it, so all I have to do is to cast ConfigurationElement type to ChannelConfig type which is far from intuitive interface. Looks like this NServiceBus.Config.ChannelCollection is kind of unfinished work, because if you look at other collections like NServiceBus.Config.MessageEndpointMappingCollection you can find there all necessary type-safe methods to work with its child elements NServiceBus.Config.MessageEndpointMapping, so I think NServiceBus team was just lazy to make the same for ChannelCollection.
UPDATE: as CreateNewElement() method is protected, I have to implement my own class inherited from ChannelCollection to make a method adding new ChannelConfig element publicly available

Reference an internal class from a Windows Workflow Activity

I'm creating a custom Workflow activity for use within TFS2010. In the same assembly I have a XAML activity and a C# code activity. The XAML activity references the code activity.
When the assembly is deployed to our clients, I only want them to be able to use the Workflow activity. The code activity is of little use by itself and would no doubt confuse them.
I thought the logical way to do this would be to set the code activity class to internal: the XAML is in the same assembly and should be able to access it. However, when I do that I get an error in the XAML saying that the type can't be found in the assembly.
Is there a way to make activities internal/hidden?
This is a common problem with XAML in all its forms. It's caused by the fact (mentioned in one of the comments) that the parser isn't in the same assembly, so has no access to internals of your assembly.
The work-around that I've seen most frequently is just to separate out what you'd like to have as internal into its own namespace. At least then your consumers aren't typically bothered by confusing types that they don't need to use. In WPF this namespace is usually the main namespace with ".Primitives" appended to it. e.g. System.Windows.Controls.Primitives.
Another tack that you could investigate is using a custom NativeActivity rather than a XAML one. Presumably this could use internal classes, since the XAML parser isn't involved. I've not tested this out though.