I've recently been using data binding in c#, and while the way I am doing it is straightforward and works, it does not feel like the best way.
For example, I have a manager class, ie UserManager which has the following interface:
class UserManager
{
public IList<User> Users { get; ...}
public AddUser(...)
public RemoveUser(...)
}
So Adduser and RemoveUser should control the list, with the Users collection as an output. I am using this collection in a binding, ie:
listBindingSource.DataSource = userManager.Users;
I am then manipulating the list via the binding, ie
listBindingSource.Add(new User(...))
This works, of course, but I am completely bypassing the UserManager and the AddUser/RemoveUser functions in there! This of course seems very wrong. What is the correct way to use databinding?
UserManager is inside a lib so I do not want to put any binding objects in there, as I feel that should be a gui thing. On the other hand, with binding, my gui has taken complete control over my collection.
As your code stands now, you can't do what you're after. At some point, the collection has to support the IBindingList interface (which is what the BindingSource object you have on the form does). If you want to make use of your UserManager class to do the manipulations, for practical purposes you'll have to change the internal data store for the Users property to use a BindingList<User> (you should still be able to return it typed as an IList<User> as you have now, just change the actual concrete implementation to BindingList<User>). Doing this will expose the IBindingList interface to the grid and it will detect changes that are made elsewhere, namely in your UserManager class.
This will, however, only cause it to pick up on changes made to the list, not to individual elements contained in the list (in other words, additions and removals will be reflected on the UI, but modifications won't be). In order to accomplish this, you need to implement IPropertyChanged on the User class (assuming it doesn't already).
Related
I'm considering switching from SQLite to Realm in my UWP applications, as Realm seems fairly easier to setup, but I'm having trouble with some limitations that so far are a deal-breaker for me, the most important one being that apparently you can't use realm objects after disposing the Realm instance that was used to retrieve them. So I wonder how am I supposed to load data to throw in a ViewModel, as after loading the data items that Realm instance would be gone.
Here's an example of a really basic ViewModel:
public class MyViewModel : ViewModelBase // Assume this has INotifyPropertyChanged setup
{
private IEnumerable<MyItem> _Items;
public IEnumerable<MyItem> Items
{
get => _Items;
private set => Set(nameof(Items), ref _Items, value);
}
public async Task LoadDataAsync()
{
using (Realm realm = await Realm.GetInstanceAsync())
{
Items = realm.All<MyItem>().ToArray();
}
}
}
Assume that MyItem is some example model, which inherits from RealmObject.
Now, if I were using SQLite, I'd have no problems whatsoever there, as once retrieved from the database, each model instance would be a standalone object that I could just store in my ViewModel. Instead, classes that inherit from RealObject are linked to their original Realm instance, so if I try to use them (ie. read one of their properties) after the source Realm instance has been disposed, everything falls apart (I get a nice Exception).
The obvious workaround would be to keep two classes for each model: one that maps to the Realm database, and another one that's a standalone object. But this has some drawbacks:
Twice the number of classes
Additional work (and memory waste) to copy each instance to the standalone class
This just seems wrong, I mean, come on
Another possibility would be to keep a singleton instance of a Realm object that is never closed, but doesn't sound like a good idea either (and it would have problems when using multiple threads too, so it's definitely not a valid solution).
I've seen that the Java version of the Realm library has some "getRawObject" method (or something like that) that allows you to get a standalone copy of a RealmObject, but still, I guess this actually creates a copy of the model instance, so it doesn't sound good either.
My question is:
Is there a way to just get the same flexibility of SQLite, where once loaded, you can pass the models around anywhere you want (including to other threads), use them in ViewModels, and then also eventually edit them and pass them back around to the database to update them on disk?
Bonus point: as another example, consider a library that loads some items from a Realm database and return them to the user. Once loaded, those objects would be read-only, meaning that even if they somehow were modified, they wouldn't be changed on the database itself. My current solution is again to copy each loaded model into another classes that doesn't inherit from RealmObject, but as I said, this is not scalable at all (imagine a large project with dozens of models, it would be impossible to do so).
In .NET, it seems to be possible to detach the managed RealmObject from the Realm only if you create a copy of it some way or another.
See https://stackoverflow.com/a/38061292/2413303
public Contact ToStandalone()
{
return new Contact()
{
companyName = this.companyName,
dateAdded = this.dateAdded,
fullName = this.fullName,
gender = this.gender,
website = this.website
};
}
Technically it doesn't have to be a different class, but it needs to be created with new.
As for having to make a copy - well, that's what you always did with SQLite too.
I have a database that contains "widgets", let's say. Widgets have properties like Length and Width, for example. The original lower-level API for creating wdigets is a mess, so I'm writing a higher-level set of functions to make things easier for callers. The database is strange, and I don't have good control over the timing of the creation of a widget object. Specifically, it can't be created until the later stages of processing, after certain other things have happened first. But I'd like my callers to think that a widget object has been created at an earlier stage, so that they can get/set its properties from the outset.
So, I implemented a "ProxyWidget" object that my callers can play with. It has private fields like private_Length and private_Width that can store the desired values. Then, it also has public properties Length and Width, that my callers can access. If the caller tells me to set the value of the Width property, the logic is:
If the corresponding widget object already exists in the database, then set
its Width property
If not, store the given width value in the private_Width field for later use.
At some later stage, when I'm sure that the widget object has been created in the database, I copy all the values: copy from private_Width to the database Width field, and so on (one field/property at a time, unfortunately).
This works OK for one type of widget. But I have about 50 types, each with about 20 different fields/properties, and this leads to an unmaintainable mess. I'm wondering if there is a smarter approach. Perhaps I could use reflection to create the "proxy" objects and copy field/property data in a generic way, rather than writing reams of repetitive code? Factor out common code somehow? Can I learn anything from "data binding" patterns? I'm a mathematician, not a programmer, and I have an uneasy feeling that my current approach is just plain dumb. My code is in C#.
First, in my experience, manually coding a data access layer can feel like a lot of repetitive work (putting an ORM in place, such as NHibernate or Entity Framework, might somewhat alleviate this issue), and updating a legacy data access layer is awful work, especially when it consists of many parts.
Some things are unclear in your question, but I suppose it is still possible to give a high-level answer. These are meant to give you some ideas:
You can build ProxyWidget either as an alternative implementation for Widget (or whatever the widget class from the existing low-level API is called), or you can implement it "on top of", or as a "wrapper around", Widget. This is the Adapter design pattern.
public sealed class ExistingTerribleWidget { … }
public sealed class ShinyWidget // this is the wrapper that sits on top of the above
{
public ShinyWidget(ExistingTerribleWidget underlying) { … }
private ExistingTerribleWidget underlying;
… // perform all real work by delegating to `underlying` as appropriate
}
I would recommend that (at least while there is still code using the existing low-level API) you use this pattern instead of creating a completely separate Widget implementation, because if ever there is a database schema change, you will have to update two different APIs. If you build your new EasyWidget class as a wrapper on top of the existing API, it could remain unchanged and only the underlying implementation would have to be updated.
You describe ProxyWidget having two functions (1) Allow modifications to an already persisted widget; and (2) Buffer for a new widget, which will be added to the database later.
You could perhaps simplify your design if you have one common base type and two sub-classes: One for new widgets that haven't been persisted yet, and one for already persisted widgets. The latter subtype possibly has an additional database ID property so that the existing widget can be identified, loaded, modified, and updated in the database:
interface IWidget { /* define all the properties required for a widget */ }
interface IWidgetTemplate : IWidget
{
IPersistedWidget Create();
bool TryLoadFrom(IWidgetRepository repository, out IPersistedWidget matching);
}
interface IPersistedWidget : IWidget
{
Guid Id { get; }
void SaveChanges();
}
This is one example for the Builder design pattern.
If you need to write similar code for many classes (for example, your 50+ database object types) you could consider using T4 text templates. This just makes writing code less repetitive; but you will still have to define your 50+ objects somewhere.
I am kinda not getting my head around this and was wondering if someone could please help me understand this.
So here is the problem, I have a class in which there are no required parameters. If user does not set the fields I can take the default value and carry on. Previously, I designed the same class as Joshua Bloch's Builder Pattern (Effective Java) (immutable object). I didn't had any good reason for making the class immutable except for the fact that I didn't wanted to have telescopic constructors and I didn't wanted to expose the data of the class.
But now, a fellow programmer friend is trying to convince me that it's okay to expose the data from the class using C# properties. I am not sure about this and I still feel that I should not be allowing user to muck with data.
Maybe I am completely wrong in my understanding. Could someone please clear my doubt about this, that whether it's good or bad to expose the data from the class?
If it is good then in what case it is good? Or else if someone can please point me to the article/book that clarifies this I would really appreciate it.
Thanks!
Expose the data in the class if it is needed or of interest outside the class, and do not do so if it is not. Expose it read-only if it's only needed to be read outside, and expose it as a full read/write property if it should be able to be changed. Otherwise, keep it in a private field.
immutable classes are easier to reason about especially in a multi tasking application, but they usually pay in performance (because when you need to change the value of a field you need to build the whole class again with the new value).
So, you could be ok or (depending on what you're coding) even better off with properties but as usual there's no silver bullet.
Settable properties are also the only way to code objects for some specific frameworks or libraries (e.g. ORMs like NHibernate), because you can't control how the library/framework initializes the object.
About constructors, C# 4 has optional parameters, that could help you avoid a long chain of constructors and also communicate much more clearly the fact that the parameters are optional.
However I can't think of many cases where you would end up with classes with a long list of optional parameters. If you find that you're coding classes like that too often (especially with the builder pattern, which is very elegant looking on the consumers' side of the class but complicates the code for the class itself) you may be using the wrong design. Are you sure you are not asking your classes to have too many responsibilities?
It basically depend on what's the purpose of your Class in the application context (could you give us more details?).
Anyway reckon that you could make a property safe from external changes by declaring is setter as private:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public string UserName { get; private set; }
It's "good" when the consumer of the class needs the data. You have two possibilities to offer properties.
if you only want to offer a property for information purpose, then choose a read only property like this:
public string MyInformation { get; private set; }
If you have the need to allow the consumer to change that property, then make the setter public like that:
public string MyChangeableInformation { get; set; }
But if the consumer has no need to get the information, then hide it in your class!
But now, a fellow programmer friend is trying to convince me that it's
okay to expose the data from the class using C# properties. I am not
sure about this and I still feel that I should not be allowing user to
muck with data.
As a rule of thumb, methods should represent actions whereas properties represent data. What your friend might have tried telling you is that you can expose the data of your class to outside world and still maintain full control on how other classes are accessing the data. In your case, as other have mentioned, you can use properties with private setters, such that the caller should not be able to modify the data.
I've created a sample app, just to test and try out some of wpf's capabilities. I was basically trying out the databinding in wpf, and did the rest of stuff more or less quickly. THen, i faced an arquitectural problem (yes, should have thought in advance before starting coding :) ) and i wanted to know what's the best refactoring solution for it.
I have a simple interface that returns a list of objects, based on a defined process.
public interface IDoStuff<out T>
{
IEnumerable<T> Do(string someParam);
}
i've created a couple of implementations for this interface. Then i have a view in wpf, which has a dropdown with hardcoded values, and depending on what you select, instatiates the implementation of the interface and populates some list
foreach (var item in new IDoSTuffImplementation1()<MyObj>.Do("imp 1"))
{
MyObjs.Add(item);
}
ater on MyObjs is the DataContext for a listview, and displays things and so on and so forth, but it's out of the main question.
this is all hardcoded and not very nice. If i was ever to implement a new interface, i'd need to add it to the dropdown, and create a new foreach for that specific implementation (more duplicated code)
Ok, here's my impression on making this better/refactoring for extensibility.
I was thinking a good approach would be to use some kind of MVVM pattern, making the wpf view into a view + viewmodel. the viewmodel would use some kind of IoC like spring, which would (by xml) instantiate one specific implementation of the interface, and inject it to the viewmodel, which would then call its "Do" method and everyone happy. So this way, the only thing that would be needed to do when we implement a new component, is to add it to the xml config file.
Suggestions, Comments? what's the best approach, if any?
thanks!!
Actually I don't see any architecture changes if you provide another implementation of the interface. You already have a good architecture when using MVVM, so the task you are trying to accomplish will not change the architecture, but will extend your application using the architecture.
I suggest you change you Method to a Property instead. And assign that property to ComboBox's ItemsSource property to ease up your coding using data binding.
I need your opinion on this because I have read a lot of different things on the subject. If you have a List<T> or any kind of list within a class declaration do you make it private and then add or remove items using specific methods or do you make it public?
Your views would be much appreciated with any disadvantages/advantages of each option.
To give an example let's say we have a class Employer with private fields name and List<Employees>. My question is if we should make the employees list private or public and what the advantages/disadvantages be on either case.
for List explicitly yes it should be private depending on what the functionality you're exposing is supposed to do, interfaces such as IEnuemerable, ICollection or IList would be a better choice or if you're exposing a collection See SLaks reply.
Generally exposing internal structure and state is a bad idea and since your object of type List is both, you would want to keep it internal.
It might make sense to give the user the ability to iterate over it, to add or remove items to it but you should still keep the List internal and either expose Add/Remove methods or as a minimum expose an interface making it possible to change the type of the internal representation with out affecting the public interface.
Further more if you are exposing using an interface you should go for the narrowst possible interface.
So if the client code only needs to enumerate it. use IEnumerable if client code needs to index use ICollection and so forth.
further if you expose as an IEnumerable you should make sure that what ever you return is in fact read only by either using a read only collection class or by use of an iterator block
EDIT after update
In regards to your example. Ask yourself does it make sense that any one except the Employer can change who his employees are? to me that's in the words you've chosen already. The Employer employs the Employee and should have full control over who his/hers employees are. So in this particular case I'd keep it private and expose Hire(IEmployee employee) and Fire(IEmployee employee) that way the code plainly states the intent
If you need to expose a collection to your class' users, you should make a readonly property with a System.Collections.ObjectModel.Collection<T>.
You can then inherit this class and override InsertItem, RemoveItem, and SetItem to run custom logic when the user manipulates the collection.
If you don't want the user to be able to change the collection, you should expose a ReadOnlyCollection<T>.
In your specific example, you should probably expose a ReadOnlyCollection<Employee> with separate mutator methods in Employer.
And if all you want is for someone to be able to enumerate the list, you could expose an iEnumerable whose GetEnumerator function would simply call the list's GetEnumerator function.
As per the refactoring catalog its always better to encasulate the collections. This prevents some one from accidently currupting the data by adding or removing items from the list. If you don't need the functionality of protecting your data from accidental changes you can return a normal list.
By exposing the Add and Remove methods you get the advantage that any changes happens only through these methods.
Depends on the functionality you want. If you just want people to be able to manipulate the list, you could expose it through a read-only property (without the setter). If you want extra code to be executed when users manipulate the list, you should write your own methods, and not expose the list.