I'm struggling a little over naming classes for my MVVM application.
I have a TrainingCourse, which is called a TrainingCourseViewModel, but I can have many of these, so I have created a TrainingCourseViewManager to hold the list of courses and allow them to be added/removed. I also have an EmployeeViewController which has a reference to other view models as well as the TrainingCourseViewManager.
The EmployeeViewController essentially wraps all of the other view models and view managers and when its instantiated it gets the employee and in turn instantiates each of the view models and view managers.
The question is... What naming conventions are people using?
Should my TrainingCourseViewManager be called TrainingCoursesViewModel and should my EmployeeViewManager be called EmployeeViewModel?
Thanks
There might be a confusion over the role of view model.
Classes in your example (and in Orion's answer to that matter) seem more like actual data model. For example, it doesn't make sense for a view model to "hold the list of courses and allow them to be added/removed" - that's what data model should do. Add and remove operations on a view model wouldn't operate on the collection itself - instead, they would access and modify underlying data model.
Do properties of TrainingCourseViewModel class store actual data values, or wrap properties of some TrainingCourseDataModel class (with additional processing)? Or if you need to serialize data, would you serialize TrainingCourseViewModel objects? If former is true, you are binding directly to the data model, and there should be no 'ViewModel' suffix in names.
On the topic of naming conventions, if names become too complex, namespaces can help. For example:
namespace TrainingCourseView.ViewModel
{
class TrainingCourse {}
class Manager {}
class Controller {}
}
...
Data.TrainingCourse course;
new ViewModel.TrainingCourse(course);
Should my TrainingCourseViewManager be called TrainingCoursesViewModel and should my EmployeeViewManager be called EmployeeViewModel?
What are your window classes called? (what is your .xaml file called?)
The naming convention goes, that you create one ViewModel class per View (a view is a .xaml/.xaml.cs pair)
If you have a single window which displays a list of Employees and Training Courses, then you'd have something like this:
namespace Models
{
public class Employee : INotifyPropertyChanged { ... }
public class TrainingCourse : INotifyPropertyChanged { ... }
}
namespace ViewModels
{
// assuming you have TrainingWindow.xaml
public class TrainingWindowViewModel : INotifyPropertyChanged
{
public ObservableCollection<TrainingCourse> TrainingCourses
{ get{ return m_trainingCourses; } }
{ set{ m_trainingCourses = value; RaisePropertyChanged("TrainingCourses"); } }
...
}
// so on and so forth
}
Related
Should it be like this
public class DataAccess
{
MyDbContext ctx;
public DataAccess()
{
ctx = new MyDbContext();
}
public List<entity> GetAll()
{
return ctx.entities.ToList();
}
}
or this
public List<entity> GetAll()
{
using (var ctx = new MyDbContext())
{
return ctx.entities.ToList();
}
}
Thanks a lot and if there is a problem in my questions, please inform me so that I may improve it.
The optimal lifetime of a DbContext depends on your requirements and may vary from case to case but in general you should prefer short-lives contexts (the second code snippet in your sample code):
Entity Frameworkâs contexts are meant to be used as short-lived instances in order to provide the most optimal performance experience ...
https://msdn.microsoft.com/en-gb/data/hh949853.aspx#9
if i have a viewmodel for adding new item and another viewmodel for displaying all or filtered items (the second viewmodel's view must always reflect any changes in the collection source), should the change be communicated from viewmodel to viewmodel directly, or viewmodel to repository to the second viewmodel?
The first view model could for example add the new item to an ObservableCollection of the second view model that the view binds to. So it should add the new item to the database using the respository and also add the new entity object to the source collection of the second view model one way or another.
I found the following use of a wrapper class, and was wondering if it is a good practice or whether its just duplication of code for no reason.
//Class:
public class SomeClass{
public Integer someInt;
public String someString;
}
//Callout Class:
public class CalloutClass{
public SomeClass someMethod(){
//...code to do a callout to an api
SomeClass someClassObj = (SomeClass)JSON.Deserialize(APIResponse.getBody(), SomeClass.class);
return someClassObj;
}
}
//Controller:
public class SomeController {
public SomeController(){
someClassObj = calloutClassObj.someMethod();
SomeWrapper wrapperObj = new SomeWrapper();
for(SomeClass iterObj : someClassObj){
wrapperObj.someWrapperInt = iterObj.someInt;
wrapperObj.someWrapperString = iterObj.someString;
}
}
public class someWrapper{
public Integer someWrapperInt{get;set;}
public String someWrapperString{get;set;}
}
}
The wrapper class "someWrapper" could be eliminated if we just use getters and setters ({get;set;}) in "SomeClass."
Could anyone explain if there could be a reason for following this procedure?
Thanks,
James
My assumption (because, code in controller is extra pseudo) is
SomeClass is a business entity, purpose of which is to store/work with business data. By work I mean using it's values to display it (using wrapper in controller), to calculate smth in other entities or build reports... Such kind of object should be as lightweight as possible. You usually iterate through them. You don't need any methods in such kind of objects. Exception is constructor with parameter(s). You might want to have SomeObject__c as parameter or someWrapper.
someWrapper is a entity to display business entity. As for wrapper classes in controllers. Imagine, that when you display entity on edit page and enter a value for someWrapperInt property, you want to update someWrapperString property (or you can just put validation there, for example, checking if it is really Integer). Usually, as for business entity, you don't want such kind of functionality. But when user create or edit it, you may want smth like this.
Short version:
If I have ViewModel, containing its Model object and exposing its properties, how do I get the model "back" after it has been edited? If the Model-inside-ViewModel is public, it violates encapsulation, and if it is private, I cannot get it (right?).
Longer version:
I am implementing a part of an application which displays collections of objects. Let's say the objects are of type Gizmo, which is declared in the Model layer, and simply holds properties and handle its own serialization/deserialization.
In the Model layer, I have a Repository<T> class, which I use to handle collections of MasterGizmo and DetailGizmo. One of the properties of this repository class is an IEnumerable<T> Items { get; } where T will be some of the Gizmo subtype.
Now since Gizmo doesn't implement INPC, I have created the following classes in ViewModel layer:
GizmoViewModel, which wraps every public property of a Gizmo so that setting any property raises PropertyChanged accordingly;
[**] RepositoryViewModel<T>, which has an ObservableCollection<GizmoViewModel> whose CollectionChanged is listened to by a method that handles Adds, Removes and Updates to the repository.
Notice that the Model layer has a "Repository of Models", while the ViewModel layer has a "ViewModel with an ObservableCollection of ViewModels".
The doubt is related to the [**] part above. My RepositoryViewModel.CollectionChangedHandler method is as follows:
void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var added in e.NewItems)
{
var gvm = added as GizmoViewModel;
if (gvm != null)
{
//// IS ANY OF THE ALTERNATIVES BELOW THE RIGHT ONE?
// Gizmo g = gvm.RetrieveModel(); ?? proper getter ??
// Gizmo g = GetModelFromViewModel(gvm); ?? external getter ??
// Gizmo g = gvm.Model; ?? public model property ??
_gizmo_repository.Add(g);
}
}
break;
....
Besides that, if anyone can detect any MVVM smell here, I'll be happy to know.
We can deal with our Models even outside the View and ViewModel layers, so leaving the model publicly accessible from ViewModel is I believe acceptable.
Let say you are creating the Models in "DataLayer" you can pass the instance of the Model to the ViewModel. To illustrate my point:
///Models ////////////////////////////
public interface IGizmo{}
public class Gizmo:IGizmo{}
public class SuperGizmo : IGizmo {}
public class SuperDuperGizmo : IGizmo { }
//////////////////////////////////////
public interface IGizmoViewModel<out T>
{
T GetModel();
}
public abstract class GizmoViewModelBase : IGizmoViewModel<IGizmo>
{
protected GizmoViewModelBase(IGizmo model)
{
_Model = model;
}
private readonly IGizmo _Model;
public IGizmo GetModel()
{
return _Model;
}
}
public class GizmoViewModel : GizmoViewModelBase
{
public GizmoViewModel(Gizmo model)
: base(model) { }
}
public class SuperDuperGizmoViewModel : GizmoViewModelBase
{
public SuperDuperGizmoViewModel(SuperDuperGizmo model)
: base(model){}
}
Your repository of Models will be updated on whatever updates it get from the ViewModel as long as you passed the same instance. So there is no need to have a repository of ViewModels to get the updates.
Reading your code, I think there is something of a mixup regarding your ViewModel and Model separation.
So, as I understand it, when your ObservableCollection of GizmoViewModel's changes, you are trying to add the Gizmo instance of the new item back to your Model?
I would approach this differently. You should create your Gizmo instances inside your Model layer, and when you do this you should add it to the Repository.
Otherwise, you haven't provided enough information - or rather, you have provided too much but it is the wrong sort of information. You need to describe the situation in which you want to do this, where these GizmoViewModels are created, etc.
From what I can see here, your GizmoViewModel has a dependency to your Repository<T>, so why not pass in the repository when you create your view model?
public class GizmoViewModel
{
private IRepository<Gizmo> _Repo;
//Underlying model (Doesn't implement INotifyPropertyChanged)
private Gizmo _Model;
//Wrapping properties
public int MyProperty
{
get { return _Model.Property; }
set
{
_Model.Property = value;
NotifyOfPropertyChange();
}
}
...
public GizmoViewModel(IRepository<Gizmo> repo)
{
_Repo = repo;
}
public void AddToRepo()
{
_Repo.Add(_Model);
}
...
It would be even better if these methods are inside the RepositoryViewModel base class. You can really go crazy with inheritance here. Perhaps something like this:
var gvm = added as IRepositoryViewModel;
if (gvm != null)
gvm.AddToRepo();
You can then simply call AddToRepo when you need to add the view model's underlying model to the repository.
Perhaps not the most elegant solution, however if encapsulation is what's worrying you, then you need to ensure that your dependencies are properly managed.
"If the Model-inside-ViewModel is public, it violates encapsulation"
Your assertion above is completely wrong and is killing your code.
By setting the Model property in ViewModel as private, you are forced to repeat your self ( code smells ), as you will need to define in your ViewModel, the same properties as you did for your Model, effectively transforming it into a Model class that mimics the Model it is supposed to expose to the View.
In MVVM the ViewModel role is to provide the View with all the presentation data and logic that it needs and for sure the Model is fundamental part of this data, by hidding it from the View you are killing MVVM.
Every application contains some settings that are configurable. These settings can more or less put into two categories:
Appearance of application: example can be window location, window size, default options on views etc.
Business rules: these settings will be used by business logic.
In architecture that I implemented, View has its own project (WPF) and ViewModel has its own project (class library). From the lofical standpoint, View should be responsible of loading / saving view related settings, and ViewModel should be responsible for loading / saving business settings.
View settings are easy to handle. Create needed properties in Settings (app.config), and its easy to you can easily load save them.
However, ViewModel cannot access app.config settings through the built-in mechanisms that are Available in View project.
First idea I had was to make some helper methods that will allow me to read / write settings in app.config from ViewModel. What is your opinion? Am I complicating stuff here, or this is acceptable way of handling applic\tion settings?
There are three ways you could go here.
Add a reference to System.Configuration.dll and have your ViewModel project use the ConfigurationManager normally.
Have the ViewModel project ask for the configuration information it needs via constructors or other methods of Dependency Inversion, and have the View project pass it in.
Put the ViewModels and Views in the main application project.
Personally, I would go for option 3 unless there is some reason they need to be in separate assemblies. If they need to be separate, then I would favor option 1 because it's simpler.
Here's a cleaner option, if you would like to keep your assemblies separate and keep your ViewModels testable:
In your ViewModel project, add an interface which provides methods or properties for retrieving and saving business settings. Have your ViewModels accept this interface as a dependency in their constructors.
In your View project, add a class which implements this interface and talks with Settings
eg,
namespace ViewModel
{
public interface IBusinessSettingsStore
{
public string SomeSetting { get; set; }
public int AnotherSetting { get; set; }
}
public class SomeViewModel
{
private IBusinessSettingsStore _businessSettings;
public SomeViewModel(IBusinessSettingsStore businessSettings)
{
_businessSettings = businessSettings;
}
private void DoSomething()
{
Console.WriteLine(_businessSettings.SomeSetting);
_businessSettings.AnotherSetting = 10;
}
}
}
namespace View
{
public class BusinessSettingsStore : IBusinessSettingsStore
{
public string SomeSetting
{
get => Settings.Default.SomeSetting;
set => Settings.Default.SomeSetting = value;
}
public int AnotherSetting
{
get => Settings.Default.AnotherSetting;
set => Settings.Default.AnotherSetting = value;
}
}
}
I've been very impressed with this library: https://www.nuget.org/packages/UserSettingsApplied/. It basically allows you to serialize whatever you want to the user's roaming app config without any effort. It seems well thought out and well tested. This allows the view model to easily persist settings in the app.config.
FYI it is totally OK for the View project to reference View Model. More than that it is pretty much mandatory, so your view can do all of its persistence through the view model layer.
I am implementing a WPF based application using MVVMfor the UI.
I have a ViewModel that wraps each editable Model that can be edited. The VM contains all the logic for handling error notifications, "is dirty" management and so forth ..
This design supports well CRUD schenarios for simple domain Model objects that are anemic, that is, do not contain any logic.
Now, I am facing a more tricky problem cause I have a domain Model that contains logic and that logic can change the internal state of the domain Model.
Do someone have already faced this scenario ? If so, do you have some advices to handle this correctly ?
Riana
Here is how I usually deal with it:
The ViewModel layer is made of types that belong to this layer, meaning I don't ever directly use my business objects inside of a ViewModel. I map my business objects to ViewModel objects that may or may not be the exact same shape minus the behaviors. It can be argued that this violates Don't Repeat Yourself, but doing so allows you to adhere to the Single Responsibility Principle. In my opinion, SRP should usually trump DRY. The ViewModel exists to serve the view, and the model exists to serve business rules / behavior.
I create a facade/service layer that takes and returns ViewModels as arguments, but maps the ViewModels to-and-from their corresponding business object versions. This, way the non-anemic objects won't impose non view logic on the ViewModel
The dependencies would look like this:
ViewModel <--> Facade/ServiceLayer --> Business Objects
I think it is important to keep this in mind if you want to unleash the full potential of MVVM: The ViewModel is the model/abstraction of the view, not the model presented to the view.
Try using Command pattern. Your screen should be design not to edit an entity but to perform an action (command) on an entity. If you follow that principle when designing your screens, your ViewModel will have properties that should be mapped to a command object. Then, the command will be send to an (remote) facade of the domain model.
ViewModels for displaying the data could be mapped directly to the database (bypassing the domain model altogether) so that you don't need to put nasty getters in the domain model classes.
If the domain model is non-anemic, you will need to use events to communicate internal changes in the Model back to the ViewModel. That way you don't have to worry about keeping track of what operations could potentially make your VM out-of-sync with the model.
Here's a simple example:
First, a sample model:
public class NonAnemicModel
{
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name == value)
return;
_name = value;
OnNameChanged(EventArgs.Empty);
}
}
public event EventHandler NameChanged;
protected virtual void OnNameChanged(EventArgs e)
{
if (NameChanged != null)
NameChanged(this, e);
}
public void PerformNameCalculation(int chars)
{
//example of a complex logic that inadvertently changes the name
this.Name = new String('Z', chars); //makes a name of Z's
}
}
And here's a sample ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
private NonAnemicModel _model;
public NonAnemicModel Model
{
get { return _model; }
set
{
_model = value;
_model.NameChanged += (sender, args) => NotifyPropertyChanged("UserName");
}
}
public string UserName
{
get { return this.Model.Name; }
set { this.Model.Name = value; }
}
//this command would call out to the PerformNameCalculation method on the Model.
public ICommand PerformNameCalculation { get; private set; }
}
Notice that the PropertyChanged event is raised when the Name on the model changes. That way, regardless of whether the UserName setter was used, or the PerformNameCalculation command was used, the ViewModel stays in sync. The big downside to this is that you have to add many more events to your Model, but I've found that having these events in place is usually very helpful in the long run. Just be careful about memory leaks with events!