In MVC, can model make use of services to load some data into a list box of a view? - actionscript-3

Is it legal In MVC, so that a "model" make use of "services" to load some data ( from web) so that the data after loading can be passed into a list box of a "view" ?
My focus is on "Can Model make use of Services directly for such purposes?"
V.

I agree with Anshu's answer but I'm personally flexible about this kind of thing on my own projects if I plan them to be very small scale, that is it doesn't seem to always be worth the time to create the clear MVC separation. There's also MVVM based on MVC, some decent info on that on wikipedia and you can find it elsewhere http://en.wikipedia.org/wiki/Model_View_ViewModel
There's no set in stone rules when it comes to design pattern usage, but if you set your own rules and work within them (particularly adhering to MVC in one or more layers of abstraction) can be helpful particularly on large projects or where a team is involved.
So the answer to your question about a model making use of services is yes this is possible, is it conforming to a strict MVC pattern, no.
The model should simply be the structure that holds the data in whatever way the data relates to other data, that's what the model is made up of. The controller handles the dirty work of making the calls to the service and updating the model. The view simply is bound to or updated when changes to the model occur and makes use of the controller (usually in as3 by using event handlers on ui components) to make the right updates to the model (or calls to then update the model).
You'll likely have extra helper classes that may sort of fit somewhere in between or outside of the parts that make up the model the view or the controller, this is okay but you should be conscious of what purpose these serve and document them well and make sure it wouldn't make sense for them to somehow be handled more elegantly within the whole setup.

I would say, its rather the responsibility of the Controller to make use of services and populate the model with the data obtained from services.
This link should provide more clarity about the responsibilities of Model, View and controller in Actionscript-3

Related

Multiple views for the same ViewModel

Let's say I have a bunch of kittens. Perhaps I have a KittenViewModel. I want to show it as a kitten card in a card view, but also as broken down into columns in a list view. Does MvvmCross support binding the KittenViewModel to multiple views? Should I have multiple ViewModels that refer back to a single model?
Disclaimer: I know that I am replying to an old question which you may well have forgotten; this is for posterity. Also, I have limited understanding of the MVVM design pattern. I remember reading somewhere that Views and ViewModels are typically in 1-to-1 correspondence, so the conventional answer is probably "You shouldn't do that. Reconsider your design."
With that being said, I recently struggled with this for a while before coming up with a very simple solution that operates under the following assumptions: (1) you wish to use the exact same instance of a ViewModel in two separate Views; (2) for whatever reason, you cannot use a DataTemplateSelector to determine which View to use; and (3) you do not mind creating multiple Views for the same ViewModel.
The solution is to define separate data templates for the KittenViewModel as resources for whatever controls you are going to use to display the data. For example, if you have created a KittenCardView user control and intend to display it in a ContentControl, you can set the DataTemplate in a ContentControl resource, something like:
<ContentControl>
<Control.Resources>
<DataTemplate DataType="{x:Type viewmodel:KittenViewModel}">
<view:KittenCardView/>
</DataTemplate>
</Control.Resources>
</ContentControl>
The KittenColumnView (or whatever you call it) would be handled similarly. You may find it helpful to define one of the Views as a Window or App resource if typically use one and only need the other in special circumstances.

Restructuring to avoid accessing components in models

Continuing to work on my port of a CakePHP 1.3 app to 3.0, and have run into another issue. I have a number of areas where functionality varies based on certain settings, and I have previously used a modular component approach. For example, Leagues can have round-robin, ladder or tournament scheduling. This impacts on the scheduling algorithm itself, such that there are different settings required to configure each type, but also dictates the way standings are rendered, ties are broken, etc. (This is just one of 10 areas where I have something similar, though not all of these suffer from the problem below.)
My solution to this in the past was to create a LeagueComponent with a base implementation, and then extend that class as LeagueRoundRobinComponent, LeagueLadderComponent and LeagueTournamentComponent. When controllers need to do anything algorithm-specific, they check the schedule_type field in the leagues table, create the appropriate component, and call functions in it. This still works just fine.
I mentioned that this also affects views. The old solution for this was to pass the league component object from the controller to the view via $this->set. The view can then query it for various functionality. This is admittedly a bit kludgy, but the obvious alternative seems to be extracting all the info the view might require and setting it all individually, which doesn't seem to me to be a lot better. If there's a better option, I'm open to it, but I'm not overly concerned about this at the moment.
The problem I've encountered is when tables need to get some of that component info. The issue at hand is when I am saving my add/edit form and need to deal with the custom settings. In order to be as flexible as possible for the future, I don't have all of these possible setting fields represented in the database, but rather serialize them into a single "custom" column. (Reading this all works quite nicely with a custom constructor and getters.) I had previously done this by loading the component from the beforeSave function in the League model, calling the function that returns the list of schedule-specific settings, extracting those values and serializing them. But with the changes to component access in 3.0, it seems I can no longer create the component in my new beforeMarshal function.
I suppose the controller could "pass" the component to the table by setting it as a property, but that feels like a major kludge, and there must be a better way. It doesn't seem like extending the table class is a good solution, because that would horribly complicate associations. I don't think that custom types are the solution, as I don't see how they'd access a component either. I'm leaning towards passing just the list of fields from the controller to the model, that's more of a "configuration" method. Speaking of configuration, I suppose it could all just go into the central Configure data store, but that's always felt to me like somewhere that you only put "small" data. I'm wondering if there's a better design pattern I could follow that would let the table continue to take care of these implementation details on its own without the controller needing to get involved; if at some point I decide to change from the serialized method to adding all of the possible columns, it would be nice to have those changes restricted to the table class.
Oh, and keep in mind that this list of custom settings is needed in both a view and the table, so whatever solution is proposed will ideally provide a way for both of them to access it, rather than requiring duplication of code.

Using sort of factory class ( instance creator ) in an MVC

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.

Knockout viewModels, a single big one or multiple?

The project I'm working on is a single page web application developed using MVVM as design pattern.
Aside the first request for the entire page every other transaction is JSON-based, every JSON is binded using Knockout at presentation level.
At the moment we're developing the whole application using a single Knockout-viewModel, every single JSON is being parsed inside the viewModel and binded to the presentation level.
Now, considering how big is the viewModel at the moment I'm wondering if it's a good practice to split the whole thing in different (smaller) viewModels specifically binded to a single element in a page (like it's described in this article), making heavy use of the mapping plugin of Knockout to generate the empty structure (and refresh the datas).
In case this isn't the best practice, how do you suggest to manage the JSON binding? At the moment we're using $.jsonparse() to obtain an object then we push the different datas inside some observable array. But I don't think this is the best way to approach this problem.
Thank you.
I'm a big fan of fanning out complexity across lots of smaller modules, rather than a single monolithic module with all the complexity.
I tend to have multiple view models and communicate between them using the Knockout.Postbox library.

Migrating from LINQ to SQL to Entity Framework 4.0 - Tips, Documentation, etc

I tried out EF back in .NET 3.5 SP1, and I was one of the many who got frustrated and decided to learn LINQ to SQL instead. Now that I know EF is the "chosen" path forward, plus EF 4.0 has some exciting new features, I'd like to migrate my app to EF 4.0.
Can anyone suggest any good resources that are specifically targeted towards 4.0 and L2S migration? NOTE: I can find plenty of blogs and articles related to migrating from L2S to EF on .NET 3.5, but I feel like many of those were obviously dated and unhelpful to someone using 4.0.
I'd really like as much deep, under-the-hood stuff as I can get; I want to really come away feeling like I know EF 4.0 the way I currently know L2S 3.5.
TIA!
I have done loads of this very type of conversion and FWIW, I would say there are more similarities than differences. I don't think there is any definitive documentation that will make you feel like an expert in EF4, beyond the stuff that is already out there...
http://msdn.microsoft.com/en-us/library/ex6y04yf(VS.100).aspx
What I can give you are the more obvious "gotchas." Specifically, Linq2Sql wanted to combine the business layer and the data layer a lot more obviously. It really pushed you to create your own partial classes. I could go on and on about way, but the most specific reason is the way the one-to-one mapper will create public parent and child properties for all relations.
If you attempt to use any type of serialization against this model, you will like run into circular reference problems as a serializer moves from a parent to a child and then back to the parent as the Linq2Sql serialization behavior automatically includes all children in the graph. This can also be really annoying when you try to grab a customer record to check the "Name" property and automatically get all the related order records included in the graph. You can set these parent and child navigation properties to be either "public" or "internal" which means if you want access to them, but don't want the serializers to automatically create circular references, you pretty much have to access them in partial classes.
Once you start down the partial class path you generally just continue the pattern and eventually will start to add helper methods for accessing your data into your individual entity classes. Also, with the Linq2Sql DataContext being more lightweight, you often find people using some kind of Singleton pattern or Repository pattern for their context. You don't see this as much at all with EF 3.5 / 4.
So let's say you have some environment similar to the one described and you want to start converting. Well, you need to find out when your DataContext is going to be create/destroyed...some people will just start each Business Layer method with a using() statement and let the context pretty much live for the lifetime of the method. Obviously this means you can get into some hairy situations that require adding .ToList() or some other extension method to the ends of your questions you can have a fully in-memory collection of your objects to pass to a child method or whatever and even then you can have problems with attempting to update entities on a context that they weren't originally retrieved from.
You'll also need to figure out how to much of the BusinessLogic incorporated in your Linq2Sql partial classes out into another layer if it doesn't deal explicitly with the data operations. This will not be painless as you figure out when you need/don't need your context, but it is for the best..
Next, you will want to deal with the object graph situation. Because of the difference in the way lazy-loading works (they made this configurable in EF 4.0 to make it behave more like Linq2Sql for those who wanted it) you will probably need to check any implied uses of child objects in the graph from your Linq2Sql implementation and verify that it doesn't now require an explicit .Include() or a .Load() to get the child objects in the graph.
Finally, you will need to decide on a serialization solution in general. By default, the DataContracts and DataMember attributes that are generated as part of an EF model work great with WCF, but not at all great with the XmlSerializer used for things like old .asmx WebServices. Even in this circumstance you might be able to get away with it if you never need to serialize child objects over the wire. Since that usually isn't the case, you are going to want to move to WCF if you have a more SOA, which will add a whole new host of opportunies, yet headaches.
In order to deal with the partial classes situation, and the hefty DataContext and even the serialization issues, there are a number of new code-generation templates available with EF 4.0. The POCO-Entity template has a lot of people excited as it creates POCO classes, just as you'd expect (the trouble is that excludes any class or member attributes for WCF etc etc). Also, the Self-Tracking Entities model pretty much solves the context issue, because you can pass your entities around and let them remember when and how they were updated, so you can create/dispose your contexts much more freely (like Linq2Sql). As another bonus, this template is the go-to template for WCF or anything that builds on WCF like RIA Services or WCF Data Services, so they have the [DataContract], [DataMember], and [KnownType] attributes already figured out.
Here is a link to the POCO template (not included out of the box):
(EDIT: I cannot post two hyperlinks, so just visit the visualstudio gallery website and search for "ADO.NET C# POCO Entity Generator")
Be sure to read the link on the ADO.net team blog about implementing this. You might like the bit about splitting your context and your entities into separate projects/assemblies if you fall into the WebService vs. WCF Service category. The "Add Service Reference..." proxy generation doesn't do namespaces the same way "Add Web Reference..." used to, so you might like to actually reference your entity class assembly in your client app so you can "exclude types from reference libraries" or whatever on your service references so you don't get a lot of ambiguous references from multiple services which use the same EF model and expose those entities...
I know this is long and rambling, but these little gotchas were waaay more of an issue for me than remembering to use context.EntityCollection.AddObject() instead of context.EntityCollection.InsertOnSubmit() and context.SaveChanges() instead of context.SubmitChanges()...
For EF Code First, it's mostly about reverse engineering the existing tables into EF classes. EF Power Tools now does this for you:
http://msdn.microsoft.com/en-us/data/jj200620.aspx
The rest is the obvious work of modifying your existing code to use those generated classes to talk to the database instead of LINQ to SQL.