An NSCollectionViewItem is derived from NSViewController. I use it as a prototype in an NSCollectionView. It has a property called RepresentedObject. Normally, I would use something like
var set = this.CreateBindingSet<DevViewController, DevViewModel> ();
set.Bind (devTextField).To (vm => vm.Text);
set.Bind (devTextView).To (vm => vm.BigText);
to bind UI elements with the vm. In the case of the NSCollectionViewItem, I want to bind to properties in the RepresentedObject. How do I do this?
NSCollectionView.Content takes NSObject[]. I'm currently taking my List and making an NSObject[] where each item in there is NSObject.FromObject(myClass) - which itself may not be the right approach.
Thanks in advance!
Update. It seems that if I can make my NSObject a KVO'd object ala http://cocoa-mono.org/archives/153/kvc-kvo-and-cocoa-bindings-oh-my-part-1/ that the bindings would automatically work.
The general approach of MvvmCross and its binding layer is that:
it tries to work with native controls,
but it also tries to encourage you to keep your ViewModel objects independent and unaware of any native choices.
So if you're trying to use a native control which requires you to supply a NSObject[] array, and you want to display (say) a list of customers, then a reasonable design choice within MvvmCross would be:
within the ViewModel:
to use a Customer object which provides INotifyPropertyChanged
to supply a List<Customer> as a parameter on your ViewModel
within the View:
to supply a NSObject[]
somewhere between the two
find:
a way of mapping your List<> to an []
and find a way of mapping your Customer to an NSObject
this can be found either:
using inheritance of the View and providing a custom C# property for binding
or using a custom binding
or using a value converter
The challenge of mapping the Customer to an NSObject is a particularly interesting one. If your end view is looking for KVO type functionality then I believe the conversion can be done by using a small Converter class which maps ValueForKey/SetValueForKey to their .Net reflection equivalent, and which maps INotifyPropertyChanged events to their DidChangeValue NSObject equivalent. I've not personally done this... but it feels like it should be doable, and (with a little caching of PropertyInfo objects) it should probably be reasonably efficient too.
Some final notes:
if you are marshalling a lot of calls between KVO and .Net reflection and this does impact your application's performance, then you may find using Rio style Field binding might be a faster experience, or you may find that it's faster to write hard-coded non-reflection based wrappers for your specific types.
if your ViewModel collection is mutable - e.g. it supports INotifyCollectionChanged then there may also be other interesting and reasonably efficient ways you can respond to the collection change events - although your view may not support these particularly 'beautifully' without some additional animation work.
I am trying to centralize the building of all the view instances using a centralized class called Factory. Had instantiated the factory class inside model. But later on, this structure started creating problems.
So asking it here. Where should such "factory" classes be placed inside mvc. How should they interact with the model, view and controllers ?
Working with an MVC structure does not mean that you need to forget other best practices. It's just a way of structuring an application into 3 (or 4 in the case of RL) tiers that make sense and push you towards writing clean code.
Models should never ever ever do anything that is view related. A factory that spawns display objects should be placed in the view tier. When and how that factory is instantiated, initialized and used depends on a number of factors. Since you're using a DI/IOC framework, the obvious choice for instantiation is by setting up an injection rule. As to what parts will be using the factory there's a number of possibilities: it could be passed on to the context view by the context view mediator. Or you could choose to dedicate a command to do the heavy lifting. Or you could encapsulate its usage in a separate class that listens to system events and responds accordingly (a sort of view-less mediator)
One minor thing: Factory is way too generic a name for the class. It communicates no intent at all. You should choose meaningful, descriptive names for your classes. If the factory creates view instances, at the very least it should contain 'view' in its name. You have to find a name that is specific enough, but doesn't tie down to a certain implementation. It depends a little on what level the class operates.
How would I create a strongly typed class at runtime (so to be able to create instances of it)? It can't be a proxy.
Additional Info:
For example, say I want to create a Person class with first and last where both are Strings.
Context
This is for an application that lets you create the data model and custom components at runtime. This is only part of it. I need to be able to have strong typing. If that means going to the server and creating a new SWF on the server with the value objects then loading in the definition at runtime then I would but that is a lot more work if there is an alternative.
AS3Commons-Bytecode lets you generate classes at runtime: http://www.as3commons.org/as3-commons-bytecode/emit.html
I am mapping some pre-existing Business Objects to our database using Entity Framework. These object were originally using a home-grown data access method, but we wanted to try out Entity Framework on it now that it is using Code-First. It was my expectation that this would be fairly simple, but now I am having some doubts.
I am trying to use only attributes to accomplish this so that I don't have some of the mapping here, some of it there, and still more of it over there....
When I query for entities, I am getting System.Data.Entity.DynamicProxies.MyClass_23A498C7987EFFF2345908623DC45345 and similar objects back. These objects have the data from the associated record there as well as related objects (although those are DynamicProxies also).
What is happening here? Is something going wrong with my mapping? Why is it not bringing back MyBusinessObject.MyClass instead?
That has nothing to do with mapping. Those types you see are called dynamic proxies. EF at runtime derives class from every type you map and use it instead of your type. These classes has some additional internal logic inside overriden property setters and getters. The logic is needed for lazy loading and dynamic change tracking of attached entities.
This behaviour can be turned off in context instance:
context.Configuration.ProxyCreationEnabled = false;
Your navigation properties will not be loaded automatically once you do this and you will have to use eager loading (Include method in queries) or explicit loading.
Part of our core product is a website CMS which makes use of various page widgets. These widgets are responsible for displaying content, listing products, handling event registration, etc. Each widget is represented by class which derives from the base widget class. When rendering a page the server grabs the page's widget from the database and then creates an instance of the correct class. The factory method right?
Private Function WidgetFactory(typeId)
Dim oWidget
Select Case typeId
Case widgetType.ContentBlock
Set oWidget = New ContentWidget
Case widgetType.Registration
Set oWidget = New RegistrationWidget
Case widgetType.DocumentList
Set oWidget = New DocumentListWidget
Case widgetType.DocumentDisplay
End Select
Set WidgetFactory = oWidget
End Function
Anyways, this is all fine but as time has gone on the number of types of widgets has increased to around 50 meaning the factory method is rather long. Every time I create a new type of widget I go to add another couple of lines to the method and a little alarm rings in my head that maybe this isn't the best way to do things. I tend to just ignore that alarm but it's getting louder.
So, am I doing it wrong? Is there a better way to handle this scenario?
I think the question you should ask yourself is: Why am I using a Factory method here?
If the answer is "because of A", and A is a good reason, then continue doing it, even if it means some extra code. If the answer is "I don't know; because I've heard that you are supposed to do it this way?" then you should reconsider.
Let's go over the standard reasons for using factories. Here's what Wikipedia says about the Factory method pattern:
[...], it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, whose subclasses can then override to specify the derived type of product that will be created.
Since your WidgetFactory is Private, this is obviously not the reason why you use this pattern. What about the "Factory pattern" itself (independent of whether you implement it using a Factory method or an abstract class)? Again, Wikipedia says:
Use the factory pattern when:
The creation of the object precludes reuse without significantly duplicating code.
The creation of the object requires access to information or resources not appropriate to contain within the composing object.
The lifetime management of created objects needs to be centralised to ensure consistent behavior.
From your sample code, it does not look like any of this matches your need. So, the question (which only you can answer) is: (1) How likely is it that you will need the features of a centralized Factory for your widgets in the future and (2) how costly is it to change everything back to a Factory approach if you need it in the future? If both are low, you can safely drop the Factory method for the time being.
EDIT: Let me get back to your special case after this generic elaboration: Usually, it's a = new XyzWidget() vs. a = WidgetFactory.Create(WidgetType.Xyz). In your case, however, you have some (numeric?) typeId from a database. As Mark correctly wrote, you need to have this typeId -> className map somewhere.
So, in that case, the good reason for using a factory method could be: "I need some kind of huge ConvertWidgetTypeIdToClassName select-case-statement anyway, so using a factory method takes no additional code plus it provides the factory method advantages for free, if I should ever need them."
As an alternative, you could store the class name of the widget in the database (you probably already have some WidgetType table with primary key typeId anyway, right?) and create the class using reflection (if your language allows for this type of thing). This has a lot of advantages (e.g. you could drop in DLLs with new widgets and don't have to change your core CMS code) but also disadvantages (e.g. "magic string" in your database which is not checked at compile time; possible code injection, depending on who has access to that table).
The WidgetFactory method is really a mapping from a typeId enumeration to concrete classes. In general it's best if you can avoid enumerations entirely, but sometimes (particularly in web applications) you need to round-trip to an environment (e.g. the browser) that doesn't understand polymorphism and you need such measures.
Refactoring contains a pretty good explanation of why switch/select case statements are code smells, but that mainly addresses the case where you have many similar switches.
If your WidgetFactory method is the only place where you switch on that particular enum, I would say that you don't have to worry. You need to have that map somewhere.
As an alternative, you could define the map as a dictionary, but the amount of code lines wouldn't decrease significantly - you may be able to cut the lines of code in half, but the degree of complexity would stay equivalent.
Your application of the factory pattern is correct. You have information which dictates which of N types is created. A factory is what knows how to do that. (It is a little odd as a private method. I would expect it to be on an IWidgetFactory interface.)
Your implementation, though, tightly couples the implementation to the concrete types. If you instead mapped typeId -> widgetType, you could use Activator.CreateInstance(widgetType) to make the factory understand any widget type.
Now, you can define the mappings however you want: a simple dictionary, discovery (attributes/reflection), in the configuration file, etc. You have to know all the types in one place somewhere, but you also have the option to compose multiple sources.
The classic way of implementing a factory is not to use a giant switch or if-ladder, but instead to use a map which maps object type name to an object creation function. Apart from anything else, this allows the factory to be modified at run-time.
Whether it's proper or not, I've always believed that the time to use a Factory is when the decision of what object type to create will be based upon information that is not available until run-time.
You indicated in a followup comment that the widget type is stored in a database. Since your code does not know what objects will be created until run-time, I think that this is a perfectly valid use of the Factory pattern. By having the factory, you enable your program to defer the decision of which object type to use until the time when the decision can actually be made.
It's been my experience that Factories grow so their dependencies don't have to. If you see this mapping duplicating itself in other places then you have cause for worry.
try categories your widgets, maybe based on their functionality.
if few of them are logically depending on each other, create them with single construction