Where should the data be stored in MVVM? - wcf

I've got this Silverlight Prism application that is using MVVM. The model calls a WCF service and a list of data is returned.
The ViewModel is bound to the View, so the ViewModel should have a List property.
Were should I keep data returned by a WCF service in MVVM?
Should the List property be calling into the Model using its getter? Where the model has a ReturnListOfData() method that returns the data stored in the model.
Or does the ViewModel stores the data after the Model is done with calling the server?
This is a follow up on Where to put the calls to WCF or other webservices in MVVM?

Generally if I need to keep the Model objects around (I consider most things coming back from a WCF service a Model object) I will store it in my ViewModel in a "Model" property.
I've seen people go so far as to create a standard Model property on their base ViewModel type, like this (I don't do this, but it's nice):
public class ViewModel<ModelType> : INotifyPropertyChanged ...
{
//Model Property
public ModelType Model
{
...
}
}
It's really up to you. Keeping them as close to their related ViewModels is probably the thing to take away here.

It really depends on other aspects of your application. E.g. how's the data returned by ReturnListOfData() used? Are there other components interested in it? Does user update elements in the list? Can it create new elements that he'll want to save later? etc.
In the simplest case you'd just have a List property exposed by your viewmodel to view, and you'd reset that list to whatever ReturnListOfData() returned. It will probably work for a case when user simply performs a search, doesn't do anything to the data later on, and there's only one view that is interested in that data.
But suppose a user wants to be able to modify elements of that list. Clearly, you'll have to somehow track the changes in that original list, so then when user clicks save (or cancel), you'd send to the server only elements that were changed (or added) or restore the original elements if user clicks cancel. In this case you'd need a Model object, that would keep the original data, so then your viewmodel contains only its copy.

Related

Where should my SQL code go in MVC

I'm just starting to learn the MVC design pattern, and I was wondering where should my SQL code go.
For example, lets say I have a register form structure that looks like this
type Form struct {
Username string
Password string
}
I assume that the form structure is part of the model, so I have some function that goes with the form that after a user submits the form, the data gets put into the database, so my function would look something like this
func (f *Form) registerUser() {
// SQL code goes here
}
Is this the best way of doing it? I have been searching around for open source Golang web apps that utilizes the MVC pattern, but I have not be able to find one which I completely understand.
In model-view-controller pattern...
Model is for entities all your classes represent real world objects.
View is the forms and all the graphic things user can see and interact with.
Controller is for controller classes, is all the logic of the program, for the sql code as you said you can implement a dao pattern and have all the sql code in the controller package and the database class in the entities package(i leave it in the Controller class).
I assume that the form structure is part of the model, so I have some function that goes with the form that after a user submits the form, the data gets put into the database, so my function would look something like this
Another use of Model in MVC application architecture is to store reusable code. So, yes, you can store the form in Model (for example, if you reuse it multiple in views) but this makes less sense than storing form in a View and reuse it later on.
The execution backtrace would be something like
Controller processes the request - personally, I do the business logic here and also (if necessary) invoke ...
Model that handles all the data retrieval from DBMS, validation, etc. and returns processed data to Controller and ...
The View is then displayed with the respective parameters (user data, template, validator result, etc.).
User fills in the form and submits the input to Controller and ...
GOTO 1. point

Passing state between view models

Just wondering really if there's a consensus on the 'right' way to do this, for MVVM, DDD, and other philosophies . . .
So I've got a login screen, represented by a ViewModel, LoginViewModel. It can take a name and password. It also takes in through dependency injection a LoginService, that implements the logic of taking the username and password, and retrieving the Employee object.
My question is what's the 'right' way to get this information to the next view model? Let's say it's AccountSettings, which needs to know about the logged in employee. How do we encapsulate that? I've got an AccountSettingsViewModel, but should it require
a) An instance of the LoginViewModel?
b) An instance of the LoginService, which keeps a reference to the logged in employee
c) A shared object or field on a global object, like App or something?
Thanks in advance!
Personally all my view models in DDD or otherwise are simple data containers, used to restrict the data that gets sent from the application to the UI/view. I might include some code in my view models that's specific to transforming data for that view. I also consider my view models to be coupled to my views (I only mention this because I've seen 2 teams put them in their own separate project/assembly away from the views!).
If I have anything copying data, or performing actions to get the data needed for the view model, this would live in either my domain model or my application layer, probably in a service. I wouldn't ever inject a service into a view model.

DDD object validation

We are building a real-estate portal. We have Services, Mappers and Entites. At the stage we are allowing users to either
Create a property via a form.
Upload a batch file containing 1 or more properties.
So if he create a property via the form we can validate the form and if its a valid property, we can add it into our system. But if he upload via a batch file, we think that the responsibility of the form is
to validate that the user provided a file
the file type is valid
and the file size is within the allowed limits.
After this it should hand over the file to the controller or service.
Now the pending tasks are
Process the file and retrieve the contents
Validate the contents
If validated, save the properties or display an error.
So which part(s) are responsible for the above tasks?
I am thinking that the controller should do the initial file processing and pass the data to the service. This means that we will create/fetch the form object in the controller and validate the form within the controller.
Now the next section is to validate the contents, which is actually a collection of entities. So we have following ideas for this stage
Service will validate the data and create the entities, it will save them.
Or service will create the entity with the provided data and then call the validation function of the entity.
Or the service will try to create an entity with the provided data (send the data to the entity constructor), and if the data is valid, the entity will be created or will generate an error etc.
The possible issues I can think about above approaches are
If the service is validating the data, it means the service will know the inner structure of the entity, so if down the road we need to update the entity structure, we have to update the service as well. Which will introduce some sort of dependency.
In the 2nd approach, I don't think that an entity should be created at first place if it isn't valid.
In the 3rd approach, we are creating a functionality within entity's constructor, so making the entity dependent on the data. So when we need to fetch the entity from persistent, we need to provide some stub data.
Or am I over-thinking??
Now the next section is to validate the contents, which is actually a collection of entities.
The Contents, that Controller sends to Service, is a graph of objects / a structure / a plain string in the simplest case, but never a collection of business entities.
If the service is validating the data, it means the service will know the inner structure of the entity
What exactly is Service validating?
Service is validating the data means that Service ensures invariant of every structure / object that it receives.
For example, if F(T) is service method and T is structure with properties { A, B, C } that represents a triangle with three edges, then Service has to ensure the invariants (the length of each site is greater then zero and the sum of the lengths of any two sides must be greater than the length of the third side) of this structure after this structure has been deserialized.
This validation has to be done because deserializer doesn't use constructors to ensure invariants during deserialization.
When these validations are done, all objects passed to Service are valid and can be freely used in business layer directly or converted to objects (for example, entities) known to business layer.
if down the road we need to update the entity structure, we have to update the service as well. Which will introduce some sort of dependency.
This dependency is inavoidable. Since Transfer Objects and Entity Objects are separated, there always exists mapper that knows how to convert them.
Service will validate the data and create the entities, it will save them.
I'd go with this. Service validates data, converts into business layer objects, invokes business layer functions, persists changes.
It depends on what kind of constraints you're validating.
1.parameter validation like notEmpty property name or max length etc.
In this case you could extract the validation logic to a Validator object. This is useful when you have multiple property creating form(web form, file uploading), the validator may be invoked by multiple "client", but the validation logic keeps in one object.
2.business rule validation.
I prefer using domain models, you may have a look at the PhoneNumber example in this presentation

How is SaveChanges() called in BreezeController?

It appears that all the existing breezejs examples are passing entity models to and from the BreezeController.
But almost all our pages built are using some form of view models. In the days we have no BreezeJs, we retrieve the data (domain model) from a repository to populate (using AutoMapper or manually) a view model, which contains only the necessary data for that view. The WebAPI sends only the view model data over to the browser where we can populate a client-side view model (usually a knockout observable).
When saving data, we collect data from a <form> to populate an input view model, send only that data over to the server, where data in the input view model is mapped to the domain model. The update is saved by calling SaveChanges() on the DbContext entity in the repository.
Now, BreezeJs is to take over all our repository code by creating an EFContextProvider. The examples I have seen usually retrieve the domain model data and then pass it all to the client side.
[HttpGet]
public IQueryable<Item> Items() {
return _contextProvider.Context.Items;
}
It is the client-side javascript's job to build a view model.
Of course it is possible for us to build the view model at the server side:
[HttpGet]
public List<ItemViewModel> Items() {
var items = _contextProvider.Context.Items
.Include("RelatedEntity")
.ToList();
var model = new List<ItemViewModel>();
.... some code to build model from items ....
return model;
}
The benefit is that less data is transferred across the network, and we can do many manipulations on the server side. But I don't know if it is a good practice to modify this BreezeController like that. But at least, it returns data needed to list all the items.
The real trouble came when I tried to POST data back.
In the BreezeJs examples I found, they use a ko.observableArray() to store all the domain model data, let's say vm.items. Then the new record newItem is build by manager.createEntity into a domain model. After validating the data, item.entityAspect.validateEntity(), the newItem is pushed into vm.items and manager.saveChanges() is called, which somehow invokes SaveChanges() on the BreezeController.
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return _contextProvider.SaveChanges(saveBundle);
}
I find too many things have been taken over! (Laugh at me if you disagree.) My questions are:
Can I just createEntity and then saveChanges?
I only have an empty form to fill in and submit. There is certainly no need to build a whole items array on the client-side.
Can I pass an input view model as a JObject and do some server-side processing before calling _contextProvider.SaveChanges()?
It turns out to be a super long post again. Thank you for reading it all through. Really appreciate it!
Good questions. Unfortunately, our demo code seems to have obscured the real capabilities of Breeze on both client and server. Breeze is not constrained in the ways that your fear.
I don't want to repeat everything that is in our documentation. We really do talk about these issues. We need more examples to be sure.
You are describing a CQRS design. I think it over-complicates most applications. But it's your prerogative.
If you want to send ItemViewModel instead of Item, you can. If you want that to be treated as an entity on the Breeze client - have the EntityManager turn it into a KO observable and manage it in cache, change track it, validate it -, you'll have to provide metadata for it ... either on server or client. That's true for Breeze ... and every other system you can name (Ember, Backbone, etc). Soon we will make it easier to create metadata on the server for an arbitrary CLR model; that may help.
You have complete control over the query on the server, btw, whether Item or ItemViewModel. You don't have to expose an open-ended query for either. You seem to know that by virtue of your 2nd example query.
On to the Command side.
You wrote: "[the examples] use a ko.observableArray() to store all the domain model data, let's say vm.items"
That is not precisely true. The items array that you see in examples exists for presentation. The items array isn't storing anything from a Breeze perspective. In fact, after a query, the entities returned in the query response (if they are entities) are already in the manager's cache no matter what you do with the query result, whether you put them in an array or throw them away. An array plays no role whatsoever in the manager's tracking of the entities.
You wrote: "Can I just createEntity and then saveChanges?"
Of course! The EntityManager.createEntity method puts a new entity in cache. Again, the reason you see it being pushed into the items array is for presentation to the user. That array has no bearing on what the manager will save.
You wrote: "Can I pass an input view model ... and do some server-side processing before calling _contextProvider.SaveChanges()?"
I don't know what you mean by "an input viewmodel". The Breeze EntityManager tracks entities. If your "input viewmodel" is an entity, the EntityManager will track it. If it has changed and you call saveChanges, the manager will send it to the controller's SaveChanges method.
You own the implementation of the controller's SaveChanges method. You can do anything you want with that JObject which is simply a JSON.NET representation of the change-set data. I think you'll benefit from the work that the ContextProvider does to parse that object into a SaveMap. Read the topic on Customizing the EFContextProvider. Most people feel this provides what they need for validating and manipulating the client change-set data before passing those data onto the data access layer ... whether that is EF or something else.
If instead you want to create your own, custom DTO to POST to your own custom controller method ... go right ahead. Don't call EntityManager.saveChanges though. Call EntityManager.getChanges() and manipulate that change array of entities into your DTO. You'll be doing everything by hand. But you can. Personally, I'd have better things to do.

How to pass user details between objects in VB.net?

I'm redesigning an old VB6 application into VB.net and there is one thing I'm not sure on the best way to do.
In the VB6 application whenever we created a new instance of a component, we would pass in the user details (user name and the like) so we new who was performing the tasks. However, no that I'm redesigning I've created some nice class designs, but I'm having to add in user details into every class and it just looks wrong.
Is there a VB.net way of doing this so my classes can just have class specific details? Some way so that if my classes need to know who is performing a task, they can get the information themselves, rather than having it passed in whenever the objects are created?
You could put the details of the current user in a class that is accessible by all class instances of your application.
One place you could consider putting it is in the MyApplication class. You could also create a module and place it there.
Could you wrap the current user details into an object, and pass the object when you create the others? They would just keep a reference, and delegate to the user object for user-specific stuff.
That seems like the obvious way?