Where Do You Store Data in a GUI Application? - c#

I've always heard that you should separate GUI/Data/Logic components, like the MVC pattern.
So, I am wondering: In a GUI application, where do you actually store the data?
Here is an example (using C# terminology):
Suppose you have a GUI that takes user input, does some analysis, and displays results in a table. The user can have several analyses in one window, so there is a ListView at the bottom that allows the user to select which analysis is currently displayed (the selected item gets displayed).
In order to display this, the analysis data must be stored somewhere. I have always done one of two things:
Put all the data into a single object and store it in the ListViewItem's "Tag" property
Extend "ListViewItem" and just add whatever properties I need.
But, this means I am storing the data inside of the ListViewItem.
Is there a more appropriate place to keep track of the data?
I could add it as private members to the main form, but that seems like the same thing.
The only other thing I can think of is to make some global class that I can reference whenver I need to.
Thanks.

As I understand, you have some ListViewItems. Each ListViewItem is associated with your business logic object and after select one of ListViewItem you want make some operations over this buisness object. In similar situations I usually make Data Object like
struct MyDataObject
{
string Id;//very often data object need to have Identifcator, but not always
//some fields
}
and add to data object constructors for typical user input.
After that I make business logic layer contains available algorithms for this data objects. For simple projects, this is a static class like
static class MyDataObjectOperationService{
void MakeSomething(MyDataObject myDataObject);
object GetSomething(MyDataObject myDataObject);
...
}
For big projects that is usually interface. Also I usually make a data layer interface for getting this data object. For example
interface IMyDataObjectRepository{
IList<MyDataObject> GetAll();
MyDataObject GetById(string id);
//CRUD operations if it need
}
After that I put into ListViewItems ids of Data Objects and on ListViewItemClick getting selecting id, after that getting DataObject by Id using data layer classes and make some operations using business logic layer classes. If I need to save DataObject changes or create new DataObject I using data layer classes.

Related

Two ViewModels for one View

I am developing a Web-App using ASP.NET MVC and I've been trying to avoid using the ViewBag, therefore I created few viewmodels to populate my drop-downs and in general to pass the data I need in my views. At the same time I would like to keep the data binding clean and avoid properties that will not be bound to (without using include/exclude attributes) and I've been told that obviously returnmodels are great for that purpose.
So is creating two independent models for one view a bad idea? One with all the data that needs to be displayed and another one only with the fields from my form or is this an excess of form over substance and should I reconsider changing my design?
Edit: A quick example because I'm not too good at explaining
class ViewModelA{ // passed to the view and then bound to when form is submitted
List<KeyValuePair<int, string>> DropDownValues; // will be always empty while databinding
int SelectedValue; // will be always 0 when passed to the view
...
}
Should I replace ViewModelA with
class ViewModelB{ // contains data passed to the view
List<KeyValuePair<int, string>> DropDownValues;
...
}
class ReturnModel{ // contains data returned from the view
int SelectedValue;
...
}
Obviously here I could just bind directly to my model but let's assume it's more complex and the data has to be processed before saved.
I think I know what you are asking. You are saying you have a viewmodel with, lets say, these properties: Age, Name, CountryOfResidence (for dropdown), and a few more properties. But when you create a new person, you only post Age, Name, IdOfCountry to controller.
So your question is what is the point of posting the whole viewmodel, when it is not needed. Fair question.
There are many ways you can do this. Here is one way:
Create a base class with common properties (for posting)
Create a derived class with more properties for the view.
Some people will refer to 1 as Data Transfer Object (DTO). These DTO's will be shared for communication between presentation layer, service layer, business layer, data access layer etc.

Simple data manipulation: in Entity Model or Business layer?

I'm working on an asp.net MVC application that implements the traditional Data/ Business/Presentation layered approach.
One of my entity models (representing a person) contains address/contact information including a field for "State". My data source (which I have little control over) provides state values in full-text (Ex: "California" vs "CA", "Florida" vs "FL", etc).
I created a static helper class that we intend to use to transform the full-text values to their abbreviations.
My question is, where should this helper class be referenced and where should the transformation take place?
I see the following options:
Use an accessor in the model that references this static class and performs the transformation on get. Something along the lines of:
public string State
{
get
{
return StateConverter.Abbreviate(_state);
}
}
perform the conversion in the business layer whenever this entity model used
Perform the conversion in the presentation layer whenever this value is displayed
I like the simplicity of having this take place in the actual model (via get accessor), but this smells a tiny bit like business logic. The other options mean that I will have to convert this in many places (duplicating logic, traversing through people lists, etc).
Thanks.
It is okay to put it inside your model since it is just a computed field. Moreover your Abbreviate(...) method doesn't even depend on any data outside your model. Your right to put it there.

How to update model and view model in MVVM pattern?

I am struggling to implement MVVM pattern in my current project.
"ClassA" continuously gets required data from a remote device and stores this data inside it's fields. It is a model, I guess. ClassA updates required information via Update method.
"ClassB" continuously gets the data from "ClassA" and stores it in corresponding properties. Looks like it is a view model.
View is a simple MainWindow.xaml with a DataGrid inside.
I have the following questions:
1) How do I update ViewModel?
Should ClassB have an Update method, which accepts an instance of ClassA and updates corresponding fields?
2) Where do I store an instance of ClassA?
Should ClassA be a field of ClassB? If it should, then how do I update Model?
I thought of something like the following:
public void UpdateB()
{
ClassA.UpdateA();
this.FieldOne = ClassA.FieldOne;
this.FieldTwo = ClassA.FieldTwo;
}
4) Does model have it's update method at all or model just stores the data?
3) What do I do inside MainWindow.cs, aside from windows initialization? Do I update view model (ClassB) there?
I find it best to have a object representing an item in each layer of abstraction. This includes the form of the data as it exists on the disk. Remember that in MVVM, the only real goal is to promote loose coupling between the interface(User Interface) and the implementation(ViewModel functionality).
For example, if I have objects stored in XML files, I will have an object in my data access layer that exists only for the proper management of the XML data. Let's call it ObjectXml. This object only contains data in the form that is native to the data on the disk. In this case, all data has a string representation, as in the XML files.
In the model layer, you will have the data representation of the XML file in the expected data types. Let's call this Object. The property getters and setters may access and set the string representation of the data by performing conversions in both directions. This way, the data is ready to be persisted to the data source(xml file, database etc.).
In ObjectViewModel, properties may access those in Object. The viewmodel contains all the members for representing and modifying the model.
Note that ObjectXml is really only beneficial when you are only allowed to store string information, or when a suitable schema does not exist for your data types.
At the end, you have a hierarchy of containment such as the one below:
public class ObjectXml
{
[XmlArray("People"), XmlArrayItem("Person")]
public List<PersonXml> People { get; set; }
//PersonXml is an xml data model similar to this one
[XmlElement("Item")]
public string Items { get; set; }
}
Here is the model for the Xml object:
public class Object
{
private ObjectXml _xmlContext;
public Object(ObjectXml xmlContext)
{
this._xmlContext = xmlContext;
}
public List<Person> People
{
get
{
//Person requires a constructor that takes a PersonXml object in order for this to work properly
return this._xmlContext.People.Select(x => new Person(x)).ToList();
}
set
{
this._xmlContext.People = value.Select(x => new PersonXml(x)).ToList();
}
}
public double Item
{
get { return double.Parse(this._xmlContext.Item); }
set { this._xmlContext.Item = value.ToString(); }
}
}
Obviously, it's not wise to name your class Object as it's a reserved word in C#. Hopefully I've given you some ideas of how to access and update data in a robust and extensible manner.
In short, you don't need an update method at all. Also, short of constants and property backing fields, there are very few reasons to need direct field access in C# MVVM.
See below. Do not listen to people that say the ViewModel and Model need to be decoupled. The main purpose of the model is an intermediary layer that prepares data to be saved or loaded into the program and to store data in a way that is agnostic to both the data and the program functionality(ViewModel)
You do not need an update method. Use properties that access the data model and persist to the data storage(xml, database etc.) if needed.
You do not need an update method.
You should not have to do anything inside of ViewModel.cs. Only code that modifies the view should be in the codebehind. The only ViewModel you should ever access in a view is one that follows the form of MainWindowViewModel, which is more like an ApplicationViewModel that carries instances of other required viewmodels.
Finally, don't get stuck using an overcomplicated MVVM "framework" as most of the functionality is not useful or necessary.
Like stated in Yuris comment, you should not use any update method, but rather implement the INotifyPropertyChanged interface. Like the name says this notifies all subscribers when the value of a certain Property changed.
This is a nice article which contains code to a minimalistic MVVM implementation. If you have trouble implementing the pattern from scratch, try to start with this example and replace the existing classes with your own one-by-one.
As to the update mechanic inside your MainWindow.cs - you don't need any, if you specify the DataBinding in your xaml code like it is done in the example linked above.
I hope this helps you getting started!

C# Generic Data Abstraction

So essentially I'm making a WPF/MVVM Light application and I currently have a TreeView that represents a variety of different types of objects. Each of these objects is wrapped in a very generic "ViewModel" that currently just exposes their name to the TreeView display in the application.
Linked conceptually to this tree, I want to provide an Object Viewer below the tree, such that when a user selects an item in the three, the object viewer is populated with the Properties of that node and it allows the user to change and save new values to the node in question.
I'm effectively trying to create an abstraction that can take a variety of types (7 different object types) and expose their Properties AND allow the user to edit them. Essentially, I can bind the properties of this abstraction to a group of Text/Display boxes on the UI, and when the user hits save, have it call update methods on the actual underlying data objects from this middle wrapper class.
Currently, the only way I can think to accomplish this is to make a separate wrapper for each underlying object type (since they all have different Properties), and essentially hard-code the fields and update methods.
Are there any other options in terms of providing further abstraction and creating a general wrapper class capable of exposing and updating Properties from a variety of objects? Thanks.
Instead of wrapping every model in a different ViewModel, you may want to expose the model directly to the View and create a DataTemplate for each type of model, this will allow you to have different UIs for each model type without having to place an intermediate ViewModel in between. Just a suggestion.

3 layer architechture and little details like dropdown lists

So I am refactoring a little application as an example to get more practice. The purpose of the application (let's say) is to collect the data from a "sign up new user" form, save it in the database. The only limitation I have is I have to use a special custom Data Access class which communicates directly with the database and returns the data (if applicable) in a DataTable object.
I have a question regarding a little details on a form and how do they fit in into the layer architecture. For example, my form has a drop down list that's fed from the database, but at the same time drop down list doesn't represent an object per SE (unlike a User that is a object, there is a class User that has multiple methods, data members etc). I don't want to have calls to the stored procedure right there in the code behind but I also do not wish to overdo on abstraction.
What would be an elegant way to take care of these little details w/o creating a class abstraction galore.
Hope I am being clear
Funny you should ask that. I went through that issue here.
These other Stack Overflow Questions that I've answered that show other parts (tangentially related):
Getting ListView Data Items from Objects
Working with ListViews
Concatenating Properties in a DropDownList
An option for getting non-object data to the UI is to create one or more lookup classes that are a bucket or "service" for getting odd bits of data for things like drop down lists etc...
Example:
myDDL.DataSource = Lookup.GetAllCountries(); // GetAllCountries is a static method
// set name/value fields etc...
myDDL.DataBind();
Using this methodology, you can still support tier separation. It's not object oriented or elegant, but it is very practical.
I don't know what's best practice, but what I do is I have a utility class that has a method that takes as arguments a DropDownList object and an enum, so I do
FillDropDown( ddlistPhoneType, DropDownTypes.PhoneTypes );
The utility class fills the dropdowns sometimes from the database, other times from XML, and occasionally some hardcoded values. But at least the GUI doesn't have to worry about that.

Categories