Update form from class or interface - winforms

I have a winform onto which I have a number of controls across a few tabs. I am writing logic which will enable / disable some of these controls based on the combo box selections made by the user. I am guessing that writing the logic in frmMain.vb isn't best practice so I'm wondering whether I should gain access to my form's controls through:
an interface
through friend-declared properties in frmMain.vb that are accessed by another class or
Other
Any help would be welcome!

In general it is a good idea to tie your front-end code to a buisiness logic layer so that it is the logic that controls the enabling/disabling of the controls. If possible, group the controls based on what will get disabled together, then make a routine that disables them all at once, and name it well, like disableAddContactInfoArea() or SetAddContactInfoArea(boolean isEnabled). In my mind, the routine will sit in frmMain.vb.
One thing to avoid is just exposing each individual control to another class (unless, in ine case, that is all you need for a specific business process - but even then you should put it in a routine and name it well to make future edits easy and less complex). Your primary objective is to manage complexity (check out Steve McConnell's book Code complete, maybe chapter 7 for this).
An ideal would be to have a few public Subs on the frmMain.vb, only there to do exactly what needs done, then have the business logic layer call those routines on the instace of frmMain that you are using.

Related

Qooxdoo Desktop Design Best Practice

I would like to know how you are Design your Qooxdoo Code.
I don't get the right Architecture which I am satisfied with.
It is hard to encapsulate the View with logic like services.
I hope someone can give me a hint to a Pattern or something to find a good solution.
One of Qooxdoo's greatest features is a strong OO class system, so really the pattern that you use is up to you - MVC, MVVC, etc are all possible because Qooxdoo's OO system provides you the tools to implement your preferred pattern(s).
One pattern that I find very useful, especially in creating larger apps, is to define custom widgets for editing models; for example, if you have models (aka "Business Objects" etc) for Customer, Invoice, InvoiceLine, and Address having a widget for CustomerEditor, InvoiceEditor, InvoiceLineEditor, etc is really useful firstly because it encapsulates the code, but also because it supports binding.
Binding is a very powerful feature of Qooxdoo - to see why, let's assume for a moment that each one of your Editor widgets has a property called value which is the thing being edited.
In simple binding, your editor can bind properties of the model to the widgets which display and edit those properties, eg CustomerEditor bind value.firstName and value.lastName to a couple of qx.ui.form.TextField and automatically changes to the customer's firstName or lastName will be updated in the two TextField's. Binding can work the other way around too, so that changes to the TextField are copied back into the model.
There is a controller class called qx.data.controller.Form that can simplify making this happen, and optionally incorporate validation of user values and user feedback too.
If you have separate Editor widgets, you can also bind to them - for example, Customer could bind value.address to an instance of AddressEditor, and InvoiceEditor could bind the currently selected InvoiceLine to InvoiceLineEditor etc

Best Way of implementation for data synchronization and interaction between multiple user controls?

Scenario:
I have one GUI where i have multiple user controls as:
One UserControl on left side of form that contain data filter and selection feature.
Another User Control on right side display/ Report data on selection from left side user control.
Last on is Menu band that control the view of above two control on some menu selection and the view of these controls change but data remain same with some conditional modifications.
That i have do somewhat. Used a global class that have some event which will be raised to make changes/ modification in these views.
I did somewhat accordingly, but i want to implement it in a maintainable way so that if i need to make some modification in functionality then i need not to change whole system.
Is there any design pattern or Model to implement such functionality where you can maintain such type of functionality in win forms?? if yes then please provide some information with some implementation..
I know this is little subjective question, but if reference links provided then much better.
Thanks in advance.
You want a model object shared between the different parts of your UI that implements the INotifyPropertyChanged interface. Use a BindingSource to link the controls with the model.

WinForms MenuStrip Isolation to improve Code Maintainability

In Windows Forms, C#, .NET 3.5, VS2008...
What's a good way to isolate the code for a MenuStrip (or any complex control group), and it's child menu items, from the rest of my form?
For example, when I have a MenuStrip with a number of menus and each menu has a number of menu items, which all have click events, a ton of code is spewed into both the Form.Desinger.cs file and also the Form.cs file. This is not causing any problems technically, but just feels wrong to have so much stuff all dumped in one place (along with everything else in the form).
Running the Code Metrics on my entire project, the form is flagged as having the worst Maintainability index of any project file. Normally, I'd not be too dogmatic about heeding the direction of the Code Metrics tool, but in this case I totally agree.
According to Code Metrics, the form violates these best practices:
Too much class coupling
Too many lines of code
Overall low maintainability
Possible solutions to isolate the MenuStrip from the rest of the form:
Stuff it into a UserControl
Other ideas?
I think you should take care about isolate business logic from presentation logic, for instance does not place too much code in click handlers or implement commands for menu items.
Get sure your code metrics does not touch generated code or don't pay attention to bad metrics in autogenerated code.
Can you disable or filter your CodeMetrics from grabbing *.Designer.cs, for example?
If not, I would use a Factory class so that you can create these structures in one line. The down side to this, is that it reduces the functionality of the Designer. In the factory, you could name each component based on a template string + "_FileMenu", for example, so that you could set the base "name" in the Factory constructor.
To reduce code spew in your Form.cs file, consider more of a MVC approach, so that when the designer generates, say a private void button1_Click method, you abstract some business logic to other methods of other classes. So instead of moving all your files, button1_Click will call InitiateMoveFileMethod( string source, string destination ), for example.

What's the "right" way to isolate control dependencies

I've made it a personal rule to inherit every UI control before using it. In a previous life I'd always considered this one of the less useful things you could do because the justification always seemed to be "I might want to change the font on all the buttons at once"... a motivation that never paid off... once... ever.
Two recent projects have changed my mind about the practice, though. In the first, we needed a consistent "ValueChanged" event so that we could easily implement a "dirty" flag on our forms without a massive switch statement to choose between a Textbox's "TextChanged" event, or a ListBox's "SelectedIndexChanged" etc. We just wanted one consistent thing to listen for on all controls, and subclassing the built-in controls bought us that pretty easily.
In the second project, every effort was made to get by with the base controls because the UI was expected to be pretty simple, but a few months in, it became obvious that they just weren't going to cut it anymore, and we purchased the Telerik control suite. If we had inherited all the controls to begin with, then changing our derived controls to inherit from the Telerik controls would have applied the changes for us globally. Instead, we had to do some searching and replacing in all the form designers.
So here's my question: What are the relative strengths and weaknesses of
Simply adding a Class, and making it inherit from a control.
Adding a new "Custom Control" and inheriting.
Adding a new "Component" and inheriting.
All three have the same effect in the end, you get a new type of Button to put on your forms. I've seen all three used by different people, and everyone seems to think that their way is the best. I thought I should put this discussion on StackOverflow, and maybe we can nail down a concensus as a community as to which one is the "right" way.
Note: I already have my personal opinion of which is "right", but I want to see what the world thinks.
If both 1 & 2 are inheriting, then they are functionally identical, no? Should one of them be encapsulating a control? In which case you have a lot of pass-thru members to add. I wouldn't recommend it.
Peronally, I simply wouldn't add extra inheritance without a very good reason... for example, the "changed event" could perhaps have been handled with some overloads etc. With C# 3.0 this gets even cleaner thanks to extension methods - i.e. you can have things like:
public static AddChangeHandler(
this TextBox textbox, EventHandler handler) {
testbox.TextChanged += handler;
}
public static AddChangeHandler(
this SomethingElse control, EventHandler handler) {
control.Whatever += handler;
}
and just use myControl.AddChangeHandler(handler); (relying on the static type of myControl to resolve the appropriate extension method).
Of course, you could take a step back and listen to events on your own model, not the UI - let the UI update the model in a basic way, and have logic in your own object model (that has nothing to do with controls).
I use composition. I simply create a new UserControl and add the controls I need. This works fine, because:
I never use that many properties anyway, so pass-through methods are kept to a minimum.
I can start with a naive approach and refine it later.
Properties for look and feel should be set consistently across the site. Now I can set them once and for all.

Best place to bring up new window in Model View ViewModel

I have an MVVM application. In one of the ViewModels is the 'FindFilesCommand' which populates an ObservableCollection. I then implement a 'RemoveFilesCommand' in the same ViewModel. This command then brings up a window to get some more user input.
Where/what is the best way to do this whilst keeping with the MVVM paradigm? Somehow
doing:
new WhateverWindow( ).Show( )
in the ViewModel seems wrong.
Cheers,
Steve
I personally look at this scenario as one where the main window view model wants to surface a task for the end user to complete.
It should be responsible for creating the task, and initializing it. The view should be responsible for creating and showing the child window, and using the task as the newly instantiated window's view model.
The task can be canceled or committed. It raises a notification when it is completed.
The window uses the notification to close itself. The parent view model uses the notification to do additional work once the task has committed if there is followup work.
I believe this is as close to the natural/intuitive thing people do with their code-behind approach, but refactored to split the UI-independent concerns into a view model, without introducing additional conceptual overhead such as services etc.
I have an implementation of this for Silverlight. See http://www.nikhilk.net/ViewModel-Dialogs-Task-Pattern.aspx for more details... I'd love to hear comments/further suggestions on this.
In the Southridge realty example of Jaime Rodriguez and Karl Shifflet, they are creating the window in the viewmodel, more specifically in the execute part of a bound command:
protected void OnShowDetails ( object param )
{
// DetailsWindow window = new DetailsWindow();
ListingDetailsWindow window = new ListingDetailsWindow();
window.DataContext = new ListingDetailsViewModel ( param as Listing, this.CurrentProfile ) ;
ViewManager.Current.ShowWindow(window, true);
}
Here is the link:
http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx
I guess thats not of a big problem. After all, the Viewmodel acts as the 'glue' between the view and the business layer/data layer, so imho it's normal to be coupled to the View (UI)...
Onyx (http://www.codeplex.com/wpfonyx) will provide a fairly nice solution for this. As an example, look at the ICommonDialogProvider service, which can be used from a ViewModel like this:
ICommonFileDialogProvider provider = this.View.GetService<ICommonDialogProvider>();
IOpenFileDialog openDialog = provider.CreateOpenFileDialog();
// configure the IOpenFileDialog here... removed for brevity
openDialog.ShowDialog();
This is very similar to using the concrete OpenFileDialog, but is fully testable. The amount of decoupling you really need would be an implementation detail for you. For instance, in your case you may want a service that entirely hides the fact that you are using a dialog. Something along the lines of:
public interface IRemoveFiles
{
string[] GetFilesToRemove();
}
IRemoveFiles removeFiles = this.View.GetService<IRemoveFiles>();
string[] files = removeFiles.GetFilesToRemove();
You then have to ensure the View has an implementation for the IRemoveFiles service, for which there's several options available to you.
Onyx isn't ready for release yet, but the code is fully working and usable at the very least as a reference point. I hope to release stabilize the V1 interface very shortly, and will release as soon as we have decent documentation and samples.
I have run into this issue with MVVM as well. My first thought is to try to find a way to not use the dialog. Using WPF it is a lot easier to come up with a slicker way to do things than with a dialog.
When that is not possible, the best option seems to be to have the ViewModel call a Shared class to get the info from the user. The ViewModel should be completely unaware that a dialog is being shown.
So, as a simple example, if you needed the user to confirm a deletion, the ViewModel could call DialogHelper.ConfirmDeletion(), which would return a boolean of whether the user said yes or no. The actual showing of the dialog would be done in the Helper class.
For more advanced dialogs, returning lots of data, the helper method should return an object with all the info from the dialog in it.
I agree it is not the smoothest fit with the rest of MVVM, but I haven't found any better examples yet.
I'd have to say, Services are the way to go here.
The service interface provides a way of returning the data. Then the actual implementation of that service can show a dialog or whatever to get the information needed in the interface.
That way to test this you can mock the service interface in your tests, and the ViewModel is none the wiser. As far as the ViewModel is concerned, it asked a service for some information and it received what it needed.
What we are doing is somethng like that, what is described here:
http://www.codeproject.com/KB/WPF/DialogBehavior.aspx?msg=3439968#xx3439968xx
The ViewModel has a property that is called ConfirmDeletionViewModel. As soon as I set the Property the Behavior opens the dialog (modal or not) and uses the ConfirmDeletionViewModel. In addition I am passing a delegate that is executed when the user wants to close the dialog. This is basically a delegate that sets the ConfirmDeletionViewModel property to null.
For Dialogs of this sort. I define it as a nested class of the FindFilesCommand. If the basic dialog used among many commands I define it in a module accessible to those commands and have the command configure the dialog accordingly.
The command objects are enough to show how the dialog is interacting with the rest of the software. In my own software the Command objects reside in their own libraries so dialog are hidden from the rest of the system.
To do anything fancier is overkill in my opinion. In addition trying to keep it at the highest level often involving creating a lot of extra interfaces and registration methods. It is a lot of coding for little gain.
Like with any framework slavish devotion will lead you down some strange alleyways. You need to use judgment to see if there are other techniques to use when you get a bad code smell. Again in my opinion dialogs should be tightly bound and defined next to the command that use them. That way five years later I can come back to that section of the code and see everything that command is dealing with.
Again in the few instances that a dialog is useful to multiple commands I define it in a module common to all of them. However in my software maybe 1 out of 20 dialogs is like this. The main exception being the file open/save dialog. If a dialog is used by dozens of commands then I would go the full route of defining a interface, creating a form to implement that interface and registering that form.
If Localization for international use is important to your application you will need to make sure you account for that with this scheme as all the forms are not in one module.

Resources