Strongly Typed Controls in .NET - c#

I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code.
What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item.
Then you go off and may display some DisplayMember and a ValueMember and so on.
If I want to retrieve that value later I need to typecast my object back to what it was. Like with strings getting the value takes
string value = (string)combobox1.SelectedItem;
Since there are generics in the Framework for quite some time now, I still wonder why in the Hell not one control from the standard toolbox is generic.
I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object. But everytime I need to access that object I then need another typecast.
Why cant I just create a ComboBox or ListView with items of type ListViewItem
Am I missing something here or is this just another example of not perfectly well thought through controls?

While the criticism of "didn't use generics" can't be fairly applied to controls developed before their existence... one must wonder about WPF controls (new in .NET 3.0, after generics in .NET 2.0).
I checked out the AddChild method in ComboBox. It takes an object parameter (ugh).
This control is intended to be used primarily via XAML. Was this done this way because there is no way to specify a type parameter in XAML? (aside, is there no way to specify a type parameter in XAML?)
Sorry to have no definitive "Why" answer, just sharing the common misery of needing to cast when working with the UI.

I dont think you're missing anything.
It's just that these classes were created back in the pre-Generics days, and WinForms is simply not cutting edge enough for MS to spend a lot of time changing or extending the API.

I often create wrapper classes for controls. This allows me to use generics. This is often in conjunction with Reflection, which is not type safe at compile time, but can be at run time.

A common source of this problem, I think, is not separating your view/presentation logic from your in-memory data model logic. Which, unfortunately, is an architecture fault that WinForms and the Visual Studio GUI designer are complicit in.
WinForms and the VS designer do not encourage the programmer to separate the management of their data objects from the form classes themselves. It would probably be better if the ComboBox ListViewItem objects didn't offer any support for arbitrary objects, either via generics or Object collections..
Unless you are hacking together something of limited use and lifetime, you should try to avoid storing references to individual data objects right in your controls or forms. They should be managed separately, and if they need to be referenced, it should be done via a model management class designed for the particular type of view class you're working with.
A simple-ish bandage for the problem, though, might be to "map" the text representations that you place into the ComboBox or ListView to the original objects, using a Dictionary field member on your Form class. It's not an ideal solution, but gives you at least a half-step of indirection between your data and your UI controls, which can make your code easier to maintain.
Edit: This is admittedly separate from the ListViewItemCollection class exposing Object instances... The official defense is likely to be that they wanted to support the standard IEnumerable and ICollection interfaces. But there's no reason they couldn't have also provided type-specific overrides of these methods, since it is designed explicitly to store ListViewItem instances. So I have no answer for you on that particular question.

Well, if you data-bind your controls to a DataBindingSource, you can get at your data that way, but AFAIK that's still not strongly typed. If you are displaying multiple parameters/aspects of a single business object, you can bind to that, then access the (strongly typed) members instead -- of course, this all goes back to Turbulent Intellect's answer, which is better separation between model and view. Still, I agree that generic-based typing would help.

It is possible (you can make your own generic controls, if you wish), but the form designer that comes with Visual Studio will freak out if you do this. You'll have to do stuff without it.
You aren't the first one to think of this, and Microsoft has already received a fair share of criticism from the public for this. Let's hope they add support for this in the future.

Related

When using protobuf-net, how do I know what fields will be updated (or have been updated) when using merge on an existing object

Using Protobuf-net, I want to know what properties of an object have been updated at the end of a merge operation so that I can notify interested code to update other components that may relate to those updated properties.
I noticed that there are a few different types of properties/methods I can add which will help me serialize selectively (Specified and ShouldSerialize). I noticed in MemberSpecifiedDecorator that the ‘read’ method will set the specified property to true when it reads. However, even if I add specified properties for each field, I’d have to check each one (and update code when new properties were added)
My current plan is to create a custom SerializationContext.context object, and then detect that during the desearalization process – and update a list of members. However… there are quite a few places in the code I need to touch to do that, and I’d rather do it using an existing system if possible.
It is much more desirable to get a list of updated member information. I realize that due to walking down an object graph that may result in many members, but in my use case I’m not merging complex objects, just simple POCO’s with value type properties.
Getting a delta log isn't an inbuilt feature, partly because of the complexity when it comes to complex models, as you note. The Specified trick would work, although this isn't the purpose it was designed for - but to avoid adding complexity to your own code,that would be something best handled via reflection, perhaps using the Expression API for performance. Another approach might be to use a ProtoReader to know in advance which fields will be touched, but that demands an understanding of the field-number/member map (which can be queried via RuntimeTypeModel).
Are you using habd-crafted models? Or are you using protogen? Yet another option would be to have code in the setters that logs changes somewhere. I don't think protogen currently emits partial method hooks, but it possibly could.
But let me turn this around: it isn't a feature that is built in right now, and it is somewhat limited due to complexity anyway, but: what would a "good" API for this look like to you?
As a side note: this isn't really a common features in serializers - you'd have very similar challenges in any mainstream serializer that I can think of.

Asp.Net MVC Property Grid Replacement

I'm currently migrating an old forms application for MVC. The forms application has a property grid, which automatically binds to an object. The object has [Category] attributes assigned to each property. The object is also very complex.
Is it better to build the View for this from scratch or use reflection to generate the UI. Personally, I prefer to build it using HTML, but the object is very big. If it is still preferable to build the entire UI using #Html.TextBoxFor(), then that's the way I'll do.
Also, I might end up creating a ViewModel for this, but that's a maybe.
Thanks!
It depends! Do you have many similar objects that can benefit from reflection? Is that code is going to be reused many times over in different views? If yes, do reflection.
Otherwise path down reflection will take you more time to work out. And given that you already have required html, just use it! Keep it simple.

Is it good practice to use reflection in your business logic?

I need to work on an application that consists of two major parts:
The business logic part with specific business classes (e.g. Book, Library, Author, ...)
A generic part that can show Books, Libraries, ... in data grids, map them to a database, ...).
The generic part uses reflection to get the data out of the business classes without the need to write specific data-grid or database logic in the business classes. This works fine and allows us to add new business classes (e.g. LibraryMember) without the need to adjust the data grid and database logic.
However, over the years, code was added to the business classes that also makes use of reflection to get things done in the business classes. E.g. if the Author of a Book is changed, observers are called to tell the Author itself that it should add this book to its collection of books written by him (Author.Books). In these observers, not only the instances are passed, but also information that is directly derived from the reflection (the FieldInfo is added to the observer call so that the caller knows that the field "Author" of the book is changed).
I can clearly see advantages in using reflection in these generic modules (like the data grid or database interface), but it seems to me that using reflection in the business classes is a bad idea. After all, shouldn't the application work without relying on reflection as much as possible? Or is the use of reflection the 'normal way of working' in the 21st century?
Is it good practice to use reflection in your business logic?
EDIT: Some clarification on the remark of Kirk:
Imagine that Author implements an observer on Book.
Book calls all its observers whenever some field of Book changes (like Title, Year, #Pages, Author, ...). The 'FieldInfo' of the changed field is passed in the observer.
The Author-observer then uses this FieldInfo to decide whether it is interested in this change. In this case, if FieldInfo is for the field Author of Book, the Author-Observer will update its own vector of Books.
The main danger with Reflection is that the flexibility can escalate into disorganized, unmaintainable code, particularly if more junior devs are used to make changes, who may not fully understand the Reflection code or are so enamored of it that they use it to solve every problem, even when simpler tools would suffice.
My observation has been that over-generalization leads to over-complication. It gets worse when the actual boundary cases turn out to not be accommodated by the generalized design, requiring hacks to fit in the new features on schedule, transmuting flexibility into complexity.
I avoid using reflection. Yes, it makes your program more flexible. But this flexibility comes at a high price: There is no compile-time checking of field names or types or whatever information you're collecting through reflection.
Like many things, it depends on what you're doing. If the nature of your logic is that you NEVER compare the field names (or whatever) found to a constant value, then using reflection is probably a good thing. But if you use reflection to find field names, and then loop through them searching for the fields named "Author" and "Title", you've just created a more-complex simulation of an object with two named fields. And what if you search for "Author" when the field is actually called "AuthorName", or you intend to search for "Author" and accidentally type "Auhtor"? Now you have errors that won't show up until runtime instead of being flagged at compile time.
With hard-coded field names, your IDE can tell you every place that a certain field is used. With reflection ... not so easy to tell. Maybe you can do a text search on the name, but if field names are passed around as variables, it can get very difficult.
I'm working on a system now where the original authors loved reflection and similar techniques. There are all sorts of places where they need to create an instance of a class and instead of just saying "new" and the class, they create a token that they look up in a table to get the class name. What does this gain? Yes, we could change the table to map that token to a different name. And this gains us ... what? When was the last time that you said, "Oh, every place that my program creates an instance of Customer, I want to change to create an instance of NewKindOfCustomer." If you have changes to a class, you change the class, not create a new class but keep the old one around for nostalgia.
To take a similar issue, I make a regular practice of building data entry screens on the fly by asking the database for a list of field names, types, and sizes, and then laying it out from there. This gives me the advantage of using the same program for all the simpler data entry screens -- just pass in the table name as a parameter -- and if a field is added or deleted, zero code change is required. But this only works as long as I don't care what the fields are. Once I start having validations or side effects specific to this screen, the system is more trouble than it's worth, and I'm better off to fall back to more explicit coding.
Based on your edit, it sounds like you are using reflection purely as a mechanism for identifying fields. This is as opposed to dynamic behavior such as looking up the fields, which should be avoided when possible (since such lookups usually use strings which ruin static type safety). Using FieldInfo to provide an identifier for a field is fairly harmless, though it does expose some internals (the info class) in a way that is not entirely ideal.
I tend not to use reflection where i can help it. by using interfaces and coding against these i can do a lot of things that some would use reflection for.
But im a big fan of if it works, it works.
Also by using reflection you probably have something that can adapt fairly easily.
Ie the only objection most would have is fairly religious ... and if your performance is fine and the code is maintainable and clear .... who cares?
Edit: based on your edit i would indeed use interfaces to achieve what you want. Unless i misunderstand you.
I think it is a good idea to stay away from Reflection when possible, but dont be afraid to resort to it when it provides a better or more flexible solution to your problem. The performance hit for anything but tight loop operations is likely to be minimal in the overall scheme of an application or Web Form request.
Just a good article to share about reflection -
http://www.simple-talk.com/dotnet/.net-framework/a-defense-of-reflection-in-.net/
I tend to use interfaces in my business layer and leave the reflection to my presentation layer. This is not an absolute but rather a guideline.

Add a property to already created Type at runtime C# ASP.NET

I had a requirement of generating classes and its objects at runtime. Hence, looking at this article I created the same. (using )
I am storing all created types in a list.
But now the other requirement is to add properties to already created Types.
This is for the reason, if i want to use say Class A as a property Type in Class B and say Both in Class C.
I read a lot of articles on the same but have not yet come to a solution
Any Help will be appreciated.
Thanks
Actually, i am in process of developing a multitenant application like LitwareHR by Microsoft.
This will be a system where admin can make sub sites with same escalation management functionality (like MS sharepoint)
Everything is done except workflows!
For data to be stored in tables, i am storing it in XML format..
Eg:
<root tablename="UserInfo">
<column name=\"Name\">Miron</column>
<column name=\"Company\">IBM</column>
</root>"
Everything from controls on the page to events to validators to web parts gets created on runtime using XSLT.
Here, the challenge comes when i need to use expression evaluator to apply workflows to it.
Eg: If UserInfo.Name == "Miron"
Everything gets created on runtime, so have to retrieve table info as an object.
Let me know if i am not clear!
If the types exist then this gets very tricky; you can't add actual properties to an existing type, but if the code that *inspects *the values uses TypeDescriptor (which most data-binding does) then you can add properties sort of via custom PropertyDescriptors - either by implementing ICustomTypeDescriptor (which requires that you do something at build), or TypeDescriptionProvider.
Both are very complex, and both also demand that you have somewhere handy to put the extra data (a property-bag).
Note that in 4.0, dynamic may have some usefulness here.
If you want to avoid this, then just wrap the types in something that looks similar but with extra properties. It'll get the job done while retaining sanity.
Yes, you can use Composition as you described to do this, but classically one would use inheritence for adding functionality to an existing type.
It is difficult to answer your question without more detail about how these classes are to be used, what will be calling them and how.
I believe you will have to derive your classes from single base. Also, to be able to:
use say Class A as a property Type in
Class B and say Both in Class C.
you will have to prepare class A, in case of it being a property of B; and classes A and B ready for them to be a property in Class C.
It would be helpful if you can add more information to your question.

How should data be synchronized between a WinForms GUI control and the client class?

What method is considered the "standard" for keeping data structures within GUI controls synchronized with the data structures that are maintained by the application?
For example:
In WinForms, if one creates a ListView instance, rather than pointing it to a data structure that represents the items to appear within the list, one must programmatically instantiate ListViewItem(s) and call an .Add method to manually replicate them, one by one, into a data structure that is internal to the ListView itself. This makes sense from a threading standpoint, and it also makes sense within the context of rendering that a control should require a specialized data structure to exist for which the control alone knows the details regarding maintenance.
However, this creates two issues:
Redundancy:
If the client class manages its own list of entities, to allow the user to select among them from the WinForms UI, this entire list must be read, converted and then recreated inside of the UI control via methods such as: .Add(ListViewItem item) Lists now occupy twice as much memory.
Complexity:
Since two lists now exist, one must programmatically ensure that they remain synchronized. This can be achieved with events that are fired from the client class's collection object, or a programmer can simply be careful to always add/remove from one list when they add/remove from the other.
I have seen many instances where programmers will take the shortcut of using a UI element like a ListView as the actual collection object used to maintain the list. For example, each user entered item will be immediately inserted into the ListView, and then when it comes time to access to user's entires, the application just iterates through the ListView. This method fails to apply when you are properly seperating business/application logic from UI logic.
Overall, something just doesn't seem right about storing application data within a data structure that is internal to a GUI control. Likewise, storing two lists and keeping them programmitically synchronized doesn't seem like an elegant solution either. Ideally, one would need only to supply a UI element with a reference to a list that resides within the scope of the client.
So, what is the "right" way to approach this problem?
Every UI control needs some state of its own. With complex controls (like ListView) that state is correspondingly complex. The trick is to make the maintenance of the controls state as simple as possible. With a standard ListView, that's not possible -- the programmer has to do the work.
That's one reason I wrote ObjectListView (an open source wrapper around .NET WinForms ListView). It allows you to use a ListView at a higher level where the maintenance of the controls state is invisible. An ObjectListView operates on your model objects directly:
this.objectListView1.Objects = listOfModelObjects;
this.objectListView1.SelectedObject = aPerson;
Once you can work at this level, data binding itself is no so useful. But, if you really want to use it, you can use the data-bindable DataListView from the ObjectListView project. It gives you the best of both worlds.
With an ObjectListView, there is no reason to switch to the far less interesting DataGridView. An ObjectListView gives you the ease of DataGridView with the nice UI features of a ListView, then plus some more:
Standard DataBinding might make your life a whole lot simpler here. Using a BindingList<T>, you can easily achieve two-way binding. Two-way binding makes it easy to update the UI with changes made programmatically (i.e. by the model) or by the user. The list will remain synchronized.
However, you might want to trade off your ListView for a (readonly) DataGridView if you can afford to. It will make your like a whole lot easier with DataBinding.
dataGridView.DataSource = new BindingList<T>(initialList);
I think there isn't a right approach for this problem. Generally, I'd strongly support separating the data source collection from the UI by all means. Several data binding solutions exists to put the two together.
Anyways, let me make some considerations on the points you exposed.
On Redundancy: You indeed would have 2 lists for the essentially the same entities in the mind of the user. The lists are not at all equivalent.
For a start, there won't be duplication of memory. The list on the UI side may have a reference to the original object in the data source list, but it's nothing more then a reference. The total memory consumption wouldn't be much larger than having a single collection object in the UI
Secondly, the two lists (UI vs. data source) may not have the same number of items. If you use paging in your interface, the UI list may be much smaller than the data source list.
On Complexity: Using a good data binding solution may greatly reduce the complexity of synchronizing UI with its data source. There are some cases where having the two lists separated will actually simplify your code.
Consider the possibility of having a separate window/page/user control/whatever that is responsible for editing (new or old) objects. If you only have a single collection of objects directly on your UI, this separate component would have to reference to the same UI control that holds the list. This simply doesn't makes sense.
DataBinding is the way to go. Take a look at this article, it is very helpful:
Data Binding in .NET / C# Windows Forms
Data binding provides a way for
developers to create a read/write link
between the controls on a form and the
data in their application (their data
model). Classically, data binding was
used within applications to take
advantage of data stored in databases.
Windows Forms data binding allows you
to access data from databases as well
as data in other structures, such as
arrays and collections.
(source: akadia.com)
The problem with accessing the ListView (for example) directly, is that you are modifying the "master" copy of the data in memory. This means that if your user decides to cancel their changes you need to be able roll back any changes they might have made.
So you have the choice, the added memory of two copies of the data structure or the added complexity of having to roll back on cancel.
Check out this article on data binding. For things like ListViews, you can bind to a custom class that implements one of the list interfaces. By adding support to your custom class for events you can automatically update the GUI whenever a change is made to the list (or vice versa).
I just went through this mess with a List(Of MyObject) and the ListView. The ListView is deficient in that it doesn't offer a .DataSource property like many other object containers, such as the ComboBox, ListBox, and DataGridView. I chose to drop the ListView in favor of a DataGridView, simply because I the requirements didn't require a ListView (I added a custom first column to the DataGridView to render an image, which is why I originally chose the ListView. But you are right, the extra code to keep things in synch was too much of a headache. As to your question, do what I did. Figure out if you really require a ListView by considering if you can use a DataGridView instead and meet the requirements.

Categories