AutoMapper a viable alternative to two way databinding using a FormView? - c#

I've started using the FormView control to enable two way databinding in asp.net webforms. I liked that it saved me the trouble of writing loadForm and unloadForm routines on every page. So it seemed to work nicely at the start when I was just using textboxes everywhere....but when it came time to start converting some to DropDownLists, all hell broke lose. For example, see:
Not possible to load DropDownList on FormView from code behind?
....and I had many additional problems after that.
So I happened upon an article on AutoMapper, which I know very little about yet, but from the sounds of it, this might be a viable alternative to two-way databinding a form to an domain entity object? From what I understand, AutoMapper basically operates on naming convention, so, it will look for matched names properties(?) on the source and destination objects.
So, basically, I have all my domain entities (ie: Person) with properties (FirstName, LastName, Address, etc)....what I would like to be able to do is declare my asp controls (textboxes, dropdownlists, etc) with those exact same names, and have automapper do the loading and unloading.
So if this worked, a person could just get rid of the cursed FormView control entirely, and it would be just one line of for binding and unbinding a webform.
(Yes, of course if I was using MVC I wouldn't have these problems, I know).
Caveat 1: AutoMapper would have to know the proper property name for each control type (the control itself would have the same ID as the property on the entity, but the behavior would depend on the control type), ie:
Person.FirstName --> form.FirstName..Text
Person.Country --> form.Country.SelectedValue
Person.IsVerified --> form.IsVerified.Checked
....so it would have to have the smarts to find the control on the form, determine its type, and then load/unload between the domain object and the webform control into the proper property of the control.
Caveat 2: Nested Controls - to complicate matters further, if one could pass a webform to AutoMapper (I don't yet know if you can), the source/destination controls are not necessarily in the root of the webform, so one would have to be able to perform a recursive search of all child controls on the passed webform (this is easy), returning a collection of all valid UI element type instances.
Caveat 3: User control UI elements are not public - when traversing the nested control hierarchy in #2, if you are using user controls, which do not expose their contained elements publicly (without hardcoding it so), one would have to do a FindControl for each element in the current AutoMapper collection. This one seems like a potential dealbreaker....
a) performance could be really bad (although if a User Control was found, it could be passed to the back of the queue and only processed if necessary)
b) from within an individual map function, how does one get reference to all the siblings of the current mapped element, in the current mapping function?
Any ideas??
Update
From what I've read, this seems like the path one would likely have to go down:
http://automapper.codeplex.com/wikipage?title=Custom%20Type%20Converters&referringTitle=Home
http://msdn.microsoft.com/en-us/library/ayybcxe5%28VS.71%29.aspx

I think your best long term solution would be to check out WebForms MVP - it provides a better abstraction layer over WebForms if you can't switch to an MVC environment. You would then have a much easier time mapping, as well as get the benefits of the MVP pattern.

Related

What is the correct way to pass controls around?

I am creating a new winforms application that will have datagridviews which will load matrix data, and I want the user to be able to do a bunch of operations on the data, like showing/hiding columns, editing cell values, and filtering too.
I thought of using the MVP pattern (Model, View, Presenter).
I wanted to create a presenter class, which would handle all the logic (meaning any events that the user triggers), eventually end up in the presenter which will work on the raw data (the matrices). This seems logical up to now but my question is what do I do if I want to pass the controls themselves (like the datagridviews)? Should these controls be sent the presenter class or is that bad design?
Perhaps it's better to find ways to only modify the raw data and then update my datagridviews?
It is not a good idea to pass around controls. If you're going to use a pattern such as "MVP", then you should have the "model" contain the representation of the "view". In this case if there are various details pertaining to a set of data it belongs in the model. Then you pass the model around.
Perhaps it's better to find ways to only modify the raw data and then update my datagridviews?
So, to answer this question, "yes". Use the model to wrap the data and pass it around.
Update
Specifically, with WinForms controls belong to containers, being that they are reference types and have lots of exposed events you run a HUGE risk of passing a reference from one Form to another Form. Now, imagine that the first Form is done being used and closes and disposes, it kills the reference to the control and attempts to unwire events. Do you see where I'm going with this? It quickly becomes a nightmare trying to correctly cleanup references, and un wire event handler and since controls belong to one container by design it breaks that paradigm.
It's better to have a separation of concerns. If you need a view to have certain data, it's always best to pass around the data itself...

HierarchicalDataTemplate - Ignore specific types on generation

My problem is the following: I got a Tree which has an dynamic depth of categories (each category can have sub-categories as well as entries).
Now I added a HierarchicalDataTemplate for the categories to display correctly in the TreeView. But I get a lot of empty entries, which do not apply the Template (wrong type) but show up in the tree as 'corpse'.
How can I ban them from the generation process? Because it's an abstract tree, they are of the same base-class as the categories are. So they get into the tree, because the tree always searches the "Branches"-property which contains either categories, entries or both.
Any ideas? I didn't find any event of the TreeView which probably give me the opportunity to skip various entries during generation nor any option/property of the template to do so.
Detailed Description: I got a generic Tree class. This class has branches of type "A_TreeLeaf" (abstract). The Tree's generic type must inherit A_TreeLeaf of course. My data is structured in categories (CategoryTreeLeaf) and Data (DataTreeLeaf). Each leaf can have sub-leaves (branches), of course.
Now I load my data from a database and build the tree. Each category has X sub-categories. And each category also could contain some Data. This structure helps me a lot, because I got an clear hierarchic structure of categories and data. This way it should be visualized to the user. But I want to separate Data and Categories. The TreeView should show just the categories (by an HierarchicalDataTemplate) and the ListView just the Data (by an DataTemplate). The ListView works fine, but the Tree shows some "corpse"-entries which are the DataTreeLeaf-instances.
I want to filter the DataTreeLeafs on generation or just stop the TreeView displaying them. Is there any "non-hack" solution? I don't want to copy the tree and remove the Data-leaves unless it's really necessary... because this would cause a lot of overhead work to do for me and to manage either the code behind which uses the real tree or the visualization with the fake-tree (because I need to bridge it somehow that it's updated automatically when one of both changes).
You have a unique problem... you have some data items in your hierarchical data that you don't want to display, but for some reason can't remove. If that sums up your problem, then you're doing something wrong.
In WPF, you shouldn't need to hide data items from the UI, instead you simply don't put them into the collection in the first place. It sounds like your process of filling your hierarchical data is flawed and you'd be better off fixing that at the source than trying to deal with the problems that it causes in the UI.
If you can't fix the actual process for whatever reason, then your next best option is to iterate through the data before you display it and simply remove any data elements that shouldn't be there. When using WPF, it is always best to provide your UI with data that fits the purpose.
However, if for whatever reason you can't even do that, then your last option is to simply define an additional DataTemplate for your abstract base class and just leave it empty:
<DataTemplate DataType="{x:Type YourDataTypesPrefix:YourBaseClass}">
</DataTemplate>
Of course, you'd have to define DataTemplates for each sub type, or they'd also be rendered empty.

MVVM viewmodel reference view

I am required to use the mvvm pattern. I know that the viewmodel should not care about the view from what I been reading. As a result I don't know how to solve this problem:
I have a dll that basically turns a textbox and listview into an autocomplete control:
SomeDll.InitAutocomplete<string>(TextBox1, ListView1, SomeObservableCollection);
anyways I don't know how to call that method from the viewmodel using the mvvm patter. if I reference the controls in the view I will be braking the rules.
I am new to MVVM pattern and my company requires me to follow it. what will be the most appropriate way of solving this problem?
I know I will be able to solve it by passing the entire view to the viewmodel as a constructor parameter but that will totaly break the mvvm pattern just because I need to reference two controls in the view.
What you're doing here is a pure view concern, so I'd recommend doing it in the view (i.e. the code-behind). The view knows about the VM and its observable collection, so why not let the code behind make this call?
(I'd also recommend seeing if you can get a non-code/XAML API for "SomeDll", but I have no idea how much control you might have over that)
There are two things that I'd point out here -
First, this is effectively all View-layer code. As such, using code behind isn't necessarily a violation of MVVM - you're not bridging that View->ViewModel layer by including some code in the code behind, if necessary.
That being said, this is often handled more elegantly in one of two ways -
You could wrap this functionality into a new control - effectively an AutoCompleteTextBox control. This would allow you to include the "textbox" and "listview" visual elements into the control template, and bind to the completion items within Xaml.
You could turn this into an attached property (or Blend behavior), which would allow you to "attach" it to a text box, and add that functionality (all within xaml). The items collection would then become a binding on the attached property (or behavior).

Best approach to develop WPF application [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to create a WPF application and would like some advice on the most appropriate approach.
I want to create an RSS reader that automatically refreshes when a new RSS entry is added. The problem is that I don't want to use traditional controls (listbox/listview) to display the data. I'd like the feed items to appear in panels randomly on the screen. These panels consist of several textblocks. Each panel displays one feed item.
It would look something like this:
Concept
This raises several questions:
1: Generate panels completely from code, or use a Custom Control?
I would model a class like a panel as described above. This class manually adds all controls to the form and drops the panel at a random location on the form. When a new RSS entry is added, an instance of this class gets instantiated and passes the rss information as parameters.
On the other hand, it might be better to create an UserControl for this. Is it easy to create this UserControl by code and pass it the parameters in the constructor?
2: Can my data/panel automatically update when a new RSS entry has been added online?
Right now I would refresh everything each (x) seconds and check against a collection of panels if there has to be created a new one. If so, create a new panel and drop it randomly on the form.
Is there a better way of doing this? I can use a local ObservableCollection with databinding that automatically updates a control (listbox, etc) when the collection changes, can this also be done with an online source like an RSS feed?
The most ideal way would be that my application gets notified when a new RSS entry has been added, downloads the last entry and creates a new Panel (trough code or trough a UserControl)
If this is hard thing to accomplish, I'll use the traditional refresh method.
3: Do I have to use DependencyObject/DependencyProperty?
I know DependencyObject & DependencyProperty expose some powerful functionality for UserControls, but I don't really know how to use them. Are they necessary for this kind of application?
4: Do I have to use WCF (Windows Communication Foundation)?
I'm not really experienced with "advanced" WPF stuff like advanced databindings, DependencyObjects and UserControls, but I love to learn!
I would recommend firstly looking into using the MVVM design pattern, and using an MVVM framework. Secondly, you could achieve this effect using an ItemsControl and use a Canvas as it's ItemsPanel type, then you could use a custom ItemTemplate which renders each data object using a UserControl.
The user control would have a dependency property which is the data item, and you would bind this in the item template declaration.
You could have a model which models each RSS entry (RSSEntry) and perhaps an RSSEntryViewModel which adds the x and y coordinates on the canvas.
Your screen view model would then have an ObservableCollection of RSSViewModel which you would add/delete etc to and the UI would automatically update.
You wouldn't need a service layer if you didnt want to, but as long as your view model retrieves the entries via an abstraction, it should be easy to refactor in the future.
Generate panels completely from code, or use a Custom Control? I usually try to do as much as I can in XAML declaratively, separating logic and presentation usually helps scalability of the application and code quality - but of course there are limits. UserControls generally are not supposed to have parameters in their constructors (not that they can't have them, but you have to have a parameterless constructor so the class can be instantiated from XAML).
Can my data/panel automatically update when a new RSS entry has been added online? There has to be something to send update notifications to the WPF layer, so it can update the display. In case of a RSS application, I guess you will have to manually periodically scan the RSS channels for updates (RSS is a pull technology) and in case of update add the item into the ObservableCollection which will send the appropriate update notification for you.
Do I have to use DependencyObject/DependencyProperty? No, you can use INotifyPropertyChanged. DependencyProperties are generally used in properties which will serve as binding target (the property that is declaring the binding) or in properties that will take advantage of any other DP feature - value inheritance or animation. INotifyPropertyChanged is enough for the properties that are bound to (that are named in the binding expression). Note that you can use NotifyPropertyWeaver to generate the notifications for INotifyPropertyChanged automatically - you just create the OnPropetyChanged method and the weaver will then call it whenever any property of the object is changed! And it even integrates beautifully with Visual Studio.
Do I have to use WCF (Windows Communication Foundation)? For WCF you have to have something to communicate with - it is a communication framework after all. Do you?
You should use a WPF listview (or similar; not sure which control exactly), and theme it to match your desired "panel" idea. That is one of the great strengths of WPF. Then you get all the benefits of the built-in control, with any look you want.
Bind to the ObservableCollection; how you update that observable collection is your business. I don't think RSS has a "push notifications" part of its spec, so polling is how these things are usually done. But in the end it doesn't really matter; that part of your code is completely separate from WPF, so as long as it updates the ObservableCollection, you're good.
Either DependencyObject/DependencyProperty or INotifyPropertyChanged are generally necessary for any kind of WPF application with databinding. It's worth learning them, and then maybe learning a framework that abstracts them away for you.
No; WCF has nothing to do with WPF. You can use any technology to talk to the server that you like.
1: Generate panels completely from code, or use a Custom Control?
Create two view model classes. One class will model the view of all your items, and one representing the content of a single item. The former will contain an observable collection of the latter.
Build a user control to display each.
The container view will be an ItemsControl whose ItemsSource is bound to its collection of item view models, whose ItemsPanel is a Canvas, and whose ItemContainerStyle binds Canvas.Top and Canvas.Left properties to Top and Left properties in the item view models. When a new item is added to the view model's collection, binding will automatically create a new panel for it.
The item view models will generate the random values of Top and Left themselves. (You could also have them request the values from the container when they're constructed.)
(If the term "view model" doesn't mean anything to you, you need to research the model/view/view model pattern, aka MVVM.)
2: Can my data/panel automatically update when a new RSS entry has been added online?
First off, you need to research how RSS aggregators work, since you're writing one. That will explain to you the mechanics of getting updates from RSS feeds. That problem is completely distinct from the problem of presenting the updates once you get them.
Your RSS aggregation layer will check feeds, look for new items, and when it finds new items, raise an event. Your UI layer will handle events raised by the aggregation layer and create new view model objects for every new item received.
This use of events completely decouples the two components from each other. For instance, you can test your UI by building a mock aggregator that generates test messages and having your UI listen to it instead of your real aggregator. Similarly, you can test your aggregator without building the - you can just build a listener that registers for its events and dumps items to the console.
3: Do I have to use DependencyObject/DependencyProperty?
You probably won't don't have to implement your own, no.
4: Do I have to use WCF (Windows Communication Foundation)?
Why wouldn't you?

C# How to implement a form which controls are dependant of some properties?

In my application, different controls are only used dependent of the values of properties from a particular object. The forms constructor accept this object as a parameter.
The form has always some basic functionality, no matter what properties are set of the particular object.
Now I have something like this:
if(myObject.SomeProperty)
{
myControl.Visible = true;
myOtherControl.Visible = false;
// and so on
}
At this time, the controls that are dependant of SomeProperty are buttons and tab items. However, I can imagine that in the future other controls are added to the form and are also dependant of SomeProperty.
As you might guess, I want to set this up the right way. But I don't know exactly how. How would you implement this?
There are multiple ways I can think of solving this, depending on your situation you could select the best suited to you.
1. Databinding is one elegant solution when managing the state (visibilit or other properties) of multiple control's depend on a different object. Additional details in this question
2. You could write different functions if the combination of the states is only limited to couple of cases to at most 4-5 cases. That ways you can still reason about the methods which set the state depending on the object you are depending on. Ex: Basic_Editing, Advaced_Editing, Custom_Editiong etc.
3. If the number of cases are limited you could create multiple forms (User controls) and load them on demand based on the state of the dependent property (or object you are talking about).
Just having a bunch of if else's makes your code harder to maintain, or comprehend, logically group the states so that 1. You could reason about it later, 2.Someone else understands the reason/logic 3.When there is a change required it can be localized to one of these modular methods (techniques) reducing the time to fix, and test.
I would do it like this in form constructor:
myControl.Visible = myObject.SomeProperty && !myObject.SomeOtherProperty;
myOtherControl.Visible = !myObject.SomeProperty;
....
Is it the less code and its rapidly changing.
OR
You can create separate functions that will generate controls dynamically at runtime for each form view based on object properties.
First i can see you are setting visibility on/off it means you have already controls on the form every time.. , so that not a good practice, instead create controls only when needed.
As for your scenario you can have an function like Initialize() which contains all the code for checking if showing a particular control should be shown or not and then create it and add it to Forms control collection. If any new control come to be added later you have one function to update.
A more precise answer can be given if you can provide more detail to you scenario

Categories

Resources