polymorphism with Windows Forms - c#

I'm making a project to get myself more familiar with Windows Forms and Graphic User Interfaces.
I have created this program for the Department of Motor Vehicles that uses polymorphism in CONSOLE. So when I input a taxi, it will call the base class of an industrial vehicle rather than a personal vehicle.
The program works fine in console.
But I'm wondering if that's implementable through a Graphical Interface. I know I can just have buttons with the types of vehicles, then have a new form open up to input that data for that specific type of vehicle. But that wouldn't be polymorphism....
Is this a type of project that could be done with polymorphism? and GUI's or no?

I think you would get more bang for the buck if only one form was created which handled the base class as mentioned. But it would turn on/off or make visible items as required by the derived classes. The GUI doesn't have to be polymorphic, it just needs to handle the polymorphism of the data. HTH

You'll have to be more specific about what you want to achieve. Polymorphism can be applied to most problems, if you like. Whether or not it's a good technique varies, and depends very much on how you use it. You seem to be forming ideas about how your object hierarchy will work early on, whereas I would suggest that you don't start there - instead specify what your application should do and how it should do it, and design your object model around that. It may turn out that your idea of how to represent (given your example) a taxi actually isn't useful.

There is no reason why you can't benefit from polymorphism in any object-oriented application, regardless of what user interface you elect to use. In your scenario, it may make sense to use only references to the base class in your list view, and then open up the appropriate details view suited to the specific type of the object.
Also, I recommend WPF for what it's worth. There's no use learning Windows Forms now unless you have a very good reason.

Perhaps what you are looking for is a way to dynamically build your GUI according to the type of (polymorphic) object you are passing? This can be done by using reflection, asking the object passed to the Form which attributes or properties it has and generate automatically input fields, text boxes etc. for each attribute.
For some examples, read this SO post:
Dynamic options dialog (using reflection)

Related

Best way to pass data between forms using C#

This is more of a theory based question. I am working on the design for my final project in C#, which is to create Jeopardy. My question is, what would be the best way to pass data between them? For instance, the rubric requires the game opens with an options screen after the splash shows. Here, they will select the number of players and their names. I know that in my gameform load event, I can just specify those things as parameters and pass them as arguments from the optionsform. This seems messy though, is there a more efficient way to create project wide variables that I could reference no matter the form I am currently using?
Thanks for any answers, it's always appreciated!
-- Young Padawan Coder
How about creating a separate business object (i.e. class) with either static properties or singleton pattern. You would then store all your application values there and you can refer to them from anywhere in your application without the messy work of passing around variables all over the place.

What is the best way to access fields/properties of the Game1 class in xna?

I'm making an xna game and there is going to be many classes that control the drawing and updating and such.
These classes need to be able to access the instance of the original Game1 class, so they can control the graphics device and sprite batch and stuff.
The problem is that I am going to have a network of classes, classes that call other classes, and the classes at the very bottom of the chain still need to be able to access the Game1 class for the graphics device and such.
What is the best way to do this? Just keep passing along the Game1 as a parameter, or what?
The "correct" answer from a software engineering/architecture perspective is to pass the specific resources you need as parameters into your methods. This provides many advantages - probably the greatest of which is that it decouples the various parts of your code, allowing them to be used independently of each other.
To give you an example: You might have your game. But then you might want to take your same code and make an editor, or unit tests, or any manner of other crazy tools. In many of these cases you might not even have a Game class. (To give you a concrete example, this video of mine shows you two very different ways of running the same game code - this would not be possible without proper decoupling.)
(On this basis, you should probably pass around more specific things than a class derived from Game.)
You can go a step further, if you have fairly open versioning/dependency requirements, and pass around an IServiceProvider (for example, this is what XNA passes to the constructor of ContentManager). I did a detailed analysis of why you might do this in this answer.
HOWEVER
You are not writing a library that will be used by third parties. You are writing a game. The only people who will be using your code are your own team - and you have access the source code and you can freely modify it.
This means that you are free to take some shortcuts.
In practice it is usually fine to grab a static instance of your game class, or (and this is my preferred method when I am throwing something together) static properties of your game class. And in XNA you know that you will only ever have a single instance of the game class in practice.
It is quick and easy to do this in the first place. And it is also quick and easy to go in later on and switch to doing thing the "right" way. As long as you are prepared for it. Good version control and using "Find All References" in Visual Studio are particularly helpful here.
Basically: as long as you understand that you are taking a shortcut, why you are taking it, and what the "correct" way is - then it is ok to take that shortcut.
Why not keep a static reference somewhere to game1, and everything refer to that?

WinForms: automating common chores

When adding a control to my form, currently I have to wire it up with my save and load code, with my internal data structures and I have to do this with all my controls. This scenario severely violates the DRY (don't repeat yourself) principle and can introduce subtle bugs.
I have came up with the idea of traversing all the Controls in a foreach loop, the Name property will be the key and the Text (or whatever depending on the type) will be the value in a dictionary (filtering for user input controls during the procedure). This way I will have to serialize/deserialize the dictionary to save/load it.
So, why am I asking? I am a beginner and I think there are more proven and tested methods for accomplishing the same task then what I came up with.
And sorry for my clunky English, I have not had the fortune to learn it as my first language.
Thanks for your help
note: I know about WPF, but I have to stick to .net 2.0
There are already good examples for doing that, see RealPosition. We modified this source to do form/control position saving in our project by just placing a component on the form in the designer and specifying the necessary properties there. Look at the IExtenderProvider and ISupportInitialize interfaces on MSDN too.
Ideally you want all the controls to inherit from a base class, the base class can then deal with all of this when each control is initialised. If you need the dictionary then pass the dictionary into a method, the method can then set all the various properties required on the control.
If each control inherits, then the logic is shared and DRY :)

.NET Reflection Create Class Properties

I am fairly new to reflection and I would like to know, if possible, how to create an instance of a class then add properties to the class, set those properties, then read them later. I don't have any code as i don't even know how to start going about this. C# or VB is fine.
Thank You
EDIT: (to elaborate)
My system has a dynamic form creator. one of my associates requires that the form data be accessible via web service. My idea was to create a class (based on the dynamic form) add properties to the class (based on the forms fields) set those properties (based on the values input for those fields) then return the class in the web service.
additionally, the web service will be able to set the properties in the class and eventually commit those changes to the db.
If you mean dynamically create a class, then the two options are:
Reflection.Emit - Difficult, Fast to create the class
CodeDom - Less Difficult, Slower to create the class
If you mean create an instance of an existing class, then start with Activator.CreateInstance to create an instance of the object, and then look at the methods on Type such as GetProperty which will return a PropertyInfo that you can call GetValue and SetValue on.
Update: For the scenario you describe, returning dynamic data from a web service, then I'd recommend against this approach as it's hard for you to code, and hard for statically-typed languages to consume. Instead, as suggested in the comments and one of the other answers, some sort of dictionary would likely be a better option.
(Note that when I say return some sort of dictionary, I am speaking figuratively rather than literally, i.e. return something which is conceptually the same as a dictionary such as a list of key-value pairs. I wouldn't recommend directly returning one (even if you're using WCF which does support this) because it's typically better to have full control over the XML you return.)
I know this is being overly simplified by why not just KISS and generate the required Xml to return through the Web Service and then parse the returned Xml to populate the database.
My reasoning is that for the expanded reason you suggest doing this I can see the value or reason for wanting a dynamic class?
The Execution-Time Code Generation chapter of Eric Gunnerson's book (A Programmer's Introduction to C#) has some great information on this topic. See page 14 and onwards in particular. He outlines the two main methods of accomplishing dynamic class/code generation (CodeDOM and the Reflection.Emit namespace). It also discusses the difficulty and performance of the two approaches. Have a read through that, and you ought to find everything you might need.
The real question is, what do you need to use those properties for?
What are gonna be the use cases? Do you need to bind those properties to the UI somehow? Using what kind of technology? (WPF, Windows Forms?)
Is it just that you need to gather a set of key/value pairs at runtime? Then maybe a simple dictionary would do the trick.
Please elaborate if you can on what it is you need, and I'm sure people here can come up with plenty of ways to help you, but it's difficult to give a good answer without more context.

How to avoid duplicating logic on two similar WinForms?

I have two forms, form A and form B. These forms must differ in appearance, but they share a lot of logic. The problem is that this logic is tied to the appearance (validation on button click, events being fired, etc.). For example, I have a name field, and when the save button is pressed, I need to fire an event which causes the parent form to validate the record name to avoid duplicates. Both forms need this logic, but their save buttons are in different places, and the tooltip that is shown when an error occurs also needs to appear in a different place. This is just one example, but does anyone know of a way that I can avoid copying and pasting code here? Perhaps I am missing something obvious...
You could create an object with data that is represented in both forms, and put validation logic in that object. The presentation layer should populate that object with the entered data, ask the object to validate itself, and then handle validation errors in a form-specific way.
If the common logic is UI related you need to create your own custom form class (that inherit from Form class) with the desired logic. then all you need to do is inherit that class in your forms.
If the common logic is less UI related create an internal class that encapsulates the common logic and call it from both forms.
You need to add a Controller between your 2 views and your shared model. This way you will just need to do : myController.save(); instead having to call you model object to save them in both winform.
There are few ways that I can think of to refactor these forms to share logic. You could use one or more of these in conjunction:
Create UI specific "bean" objects that wrap your business object and adds additional functionality that is shared between forms. This bean can do things like create tool tips, assist with validation, eventing, etc.
Create a helper class with common functions. Generalize the logic on the two forms to call this helper class for common functions.
Enhance your business objects to do your validation. I don't mean to say your BOs should be aware of any UI, but they could/should enforce the business rules. This might pull some of the validation logic off your forms and into a common location.
Create custom controls that are specific to the type of data with which you are working, and use those controls on the two forms.
You may also want to take a look at the CSLA Framework, I've used it pretty successfully in past projects to help reduce the amount of duplicate code between different UIs. It takes advantage of .NET's databinding capabilities, but I don't think it's required to use databinding just to get the most out of the framework.

Categories

Resources