Breaking code into manageable chunks - c#

I have a Windows Forms application written in C# and one of the forms has an enourmous amount of code with it. I have made extensive use of classes to keep the forms code to a minimum, but because the form has a number of tab pages and hundreds of controls and datagrids, etc., the code on the form itself is still extensive.
Is there any way to break this code into more manageable and smaller items, perhaps one item in the solution for each tab page, whilst keeping all the code in the same scope?

If your looking for better readability and maintainance without moving the code around too much, you could use:
#region Tab 1
#region Variables
#endregion
#region Properties
#endregion
#region Methods
#endregion
#endregion
This would allow you to minimise parts of the code you are not interested in while making changes to a certain tab. It's not perfect, but it may help.

If you are looking for the restructuring the code and its framework then you must be aware of the SOLID principles. A good article for it is S.O.L.I.D. Software Development, One Step at a Time.

You could use Partial Classes to split code into several cs files, but I really don't see to much benefit in that, only solution is to do full refactoring and remove code that has nothing to do with UI into separate classes.

You basically need to refactor. This is a common problem with classic Windows Forms applications, so you have to be disciplined and decide how to tidy up. It's not going to be an instantaneous fix.
Lookup MVC/MVP, even MVVM and learn how others break their code up. From there you can introduce a tiered architecture that suits you.
However, you aren't alone. The refactoring tools in Visual Studio or even better in ReSharper can automate a lot of the copy paste cycle, eliminating errors and automatically keeping variable names, etc. in sync.

Code which belongs to the presentation layer of a user control you can put into a class which extends the control.

Extract the code out of each tab and create a user control to contain the code for each tab. (you could even inherit from TabPage and add these to the form on init)
Then the user controls can be added in to each tab and should reduce code significantly.
The grids etc can also be turned in to user controls exposing the minimum number of methods and properties required for the other controls to access.

If you are defining form controls over and over, just create a new instance of them on your other tab.
Create getter and setter to access this.
But really, there is no problem with having lots of code for form controls, its just the way it is I think. I thought Visual Studio was supposed to generate all this for you using Windows Forms?

I personally have trouble with regions. It sometimes throws the editor and you need to close and re-open the file to reset it (I am working with Boo in SharpDevelop, and it may be specific to that), so for large forms with tabs I tend to use partial classes.
A neat trick you can do in Visual Studio/SharpDevelop file explorer is to drag the file for the partial class onto the main file for the class, so they all sit nested under MainForm (next to the .designer and .resx files) which just keeps things neater.

Related

Reducing Complexities in Single form Application

I've created a win form application which consist of a single form. We have 8 tabs to access the modules of application.
The problem is we are a team of 4 who works on this project. But since it is a single form application, only one person can use the file at a time. Is there anyother way to build application with more than one file?
Please provide some solution.
Firstly, you should probably have a separate UserControl per tab. That will give you 8 files (at least) since you have 8 tabs.
Secondly, you should be using a Model-View-Controller style architecture for Windows Forms applications. That will give you at least one controller, but likely you will have one controller per UserControl (i.e. per tab). You might even have an overall controller that manages the per-tab controllers.
You might only have one data model for the entire app, or you might have one data model per UserControl (tab).
If you did all that, you'd have a few more source files.
However, it's actually difficult to say without knowing anything about your app.
Try using user controls to make each tab modular.
Figure out what are the parameters that each tab accepts and that it exposes and then create user controls that have that behavior.
Here are couple resources to get you started
http://msdn.microsoft.com/en-us/library/aa302342.aspx
User Control vs. Windows Form
User Controls in Windows Forms - Anything similar to ASP.NET User Controls?
Even if this is a giant ball of wax, your source control tools are shoddy and breaking it up into separate classes is hard to do, you can still take advantage of a Form class being a partial class. Which means that you can spread the code over any number of source code files, not just the two files that the designer creates. So a logical organization is to move code that belongs to a particular tab in its own partial class with the same form class name and its own source code file. Some cut+paste required however when you add event handlers with the designer.
Have you considered using MDI?
MSDN Working with MDI...
Examples are in VB.Net but I'm sure it will be easy to use C# if you really want to - I'm not sure why, but... :)

Kind of live debugging possible? (Especially UI manipulation)

I would like to know if there is a way to manipulate an App's UI live while running?
I am not a designer and I have many problems sometimes regarding matching colours etc.
The next problem is that anytime I would like to change e.g. the colour of a control I have to quit the App then go to VS2012, apply my changes, build and execute it again to see simple changes.
I know that I see any changes in the designer but I have to see the resulting screen to get an impression of the whole.
Is there a way to achieve this?
Add a secret keypress while Debug flag is set, that raises a form and allows you to select controls and expose a property sheet for them. Be a bit of work to get right, and a good stick of code even using reflection. Might be better off with a storyboard type app to do your designing.
Unlike styles in WPF which can be dynamically adjusted (which made this type of run-time adjustment simple), there isn't as elegant of a solution for Windows Store apps. Ideally, you'd have all of your UI and colors, etc. defined in XAML files and not settable through other means (as it becomes a longer term maintenance issue).
I'd suggest just adding enough test data and configuration so that you can see the look and feel of the pages (with colors, etc.) at design-time. Blend and Visual Studio are now quite good at showing a very reasonable near final rendering of the elements of the application. It's generally not too difficult to do anymore.
One thing I've done in the past was to make a single page/form that contained all of the styles and controls in a large scroll viewer. Then, we set it so it was configurable to the be the first thing to run. The tweak/build cycle was pretty fast, and the results were still very manageable.

Adding controls conditionally

I am currently working on this big project (a GUI to control hardware) that was written in C# with .NET 3.5. Now the next revision of hardware will be coming, and some of the changes are such that some of the controls that we had before are not needed, and some new controls need to be added too. Since the changes are huge, it would require almost a month to go through every control and put a condition to make it visible or not.
I was wondering if there is any other way to tackle this problem easily other than manually conditioning the whole project. Thanks in advance.
If you can make the decision to make visible or invisible based on some attribute of the control, such as its name, or tag, you could write a method that could walk a window's controls, and programmatically hide the ones you wanted hidden. For controls like a label you might key on the text of the label.
Written correctly the method could be written so that it is re-entrant so that for controls that contain other controls, the method would call itself for each of the current controls children.
The hardest part about this would be to determine how to decide programmatically make the on or off decision.
If that's not possible, another solution might be to write a small app that would read the code and list the controls you want to examine, allowing you to make a decision based on your knowledge of the application. The app then could make the changes necessary to set an attribute on the control in code so that its hidden when the code is compiled.
You usually have to design for these kinds of things, and by the sounds of it, it isn't designed for this.
but quite often, this kind changes appears quite large, but often isn't THAT big of a deal.

Why does C# designer-generated code (like Form1.designer.cs) play havoc with Subversion?

My workshop has recently switched to Subversion from SourceSafe, freeing us from automatic locks. This led to concurrent editing of the Forms, which is wonderful. But when multiple developers commit their changes, the code files created by the designer (all the files named TheFormName.designer.cs) cause conflicts which are very difficult to resolve.
As far as I can tell, this is because the code generated by the designer is heavily re-arranged whenever the user modifies it, no matter how little the actual change really did.
How do I make these conflicts easier to resolve?
Is there some way to tell the designer to modify the code less?
How do you, the experienced C# teams, deal with concurrent modification of a Form?
Here are some things to try:
Make things more modular. Use components like User Controls etc. to split forms into multiple, smaller physical files.
Use presentation layer design patterns like MVP to move code out of views and into standard POCO classes.
Recent versions of SVN allow you to take hard locks - use this to avoid complex merge scenarios.
Hope that helps.
I'm pretty sure there is no silver bullet for this problem as the designer stomps all over the designer.cs.
All I can suggest is to minimise the use of the designer. Personally I only hook to events in code and only use the designer only for initialisation and positioning. As such it isn't too hard to fathom differences in a changeset ("oh, someone has added a button", "oh, someone has changed how it looks slightly").
Yep, Designer's random rearranging sure is irritating. Does Microsoft use their own tools? Does Microsoft look at what they check into version-control? It boggles the mind.
Our team's "solution" is to hand-edit the Designer files after we're done editing them, to put things back to where they were, so that the text-based diff is readable, and so concurrent changes can be merged sanely. Luckily, most of Visual Studio's rearranging is simple-minded, so this works.
Sadly, we've found that this step is necessary to verify correctness -- we've found cases where Designer silently removes things that are needed, leading to broken code. So this step has to be done in order to work around whatever data-destroying bugs lurk inside. Sigh.
Since Microsoft has a poor track record of fixing its bugs, the only solution may be to improve Mono's WinForms Designer so that it's ready for prime time.
I'm not familiar with C# or the Windows Form Designer, but looking at some designer.cs files I could find online they don't have a particularly complicated structure.
What parts of it are being re-arranged? I guess it's mostly the order of the properties in the InitializeComponent() method that's jumbled up?
If that's the case, you might be able to write a simple script that re-orders those lines alphabetically, say (especially if you never edit these files manually anyway), and use that as a pre-commit hook script in Subversion.
Um, right... scratch that. The big red box at the bottom of that section says you're not supposed to modify transactions in hook scripts. But you might be able to find another way to run that script somewhere between the designer.cs file being changed and it being committed.
Edit:
Actually, given scraimer's comment on this:
Total hack, but in the worst case, just before a merge, I could sort BOTH files, and make the merge simply a line-by-line affair...
Can't you let Subversion set an external merge program? I've been using KDiff3, which can run a preprocessor command before doing diffs or merges, so you could automate that process.
It's true that the designer sometimes messes up the order of the controls in the code, which causes the file to look very different compared to a previous version. This indeed is a problem if the file is under version control.
However, I found that the designer works quite reliably even in very large forms and user-controls if you follow some rules, and in those rare case where it does not, I have a easy way to force the designer into arranging the controls in the "correct" order again.
My rules:
The comment at the top of InitializeComponent() in every .designer.cs says: do not modify the contents of this method with the code editor. Well, if you know what you're doing, then it's absolutely no problem to edit this file manually, because this is what you need to do. Just make sure you have a backup.
Typically, when you create a form or UC, you add some controls here and there and move them around until you find a nice arrangement. But in the .designer.cs file, the controls are ordered by the order of their creation, and not by your logic how they belong together.
After finishing the creation of the form or UC, I reorder both the declarations (at the bottom of the file) and instantiations of the controls and their adding to the respective parent control (both in InitializeComponent()) until they are in the order that I want them to have. This makes it much easier to find them if you have to change a property of a control in the code.
And it also makes it easier for version control, because you may easily see what part of your form or UC was changed just by seeing the place (rather towards top or bottom of the file?) of the change in a file comparison view.
But changing the order in these 2 sections does not automatically change the order of all the parametrization code that comes after the instantiation part in InitializeComponent(). This will be done when you execute the solution to the OP's problem, which is described next.
If you work with rule #2, then you need to do the same finishing work that you need to do when you encounter the problem that the OP describes:
You have to force the designer to arrange controls in the order that they have in the declaration and instantiation.
This can be done in a quite simple way (which worked for me in 99% of the cases so far):
Save all files of the form or UC
open the designer view
move one of the controls (e.g. by selecting it and hitting 1x left arrow key)
optional: look at the .designer.cs file and/or save the form or UC
move the control back to have your intended design (e.g. by hitting 1x right arrow key)
save the form or UC
The designer will rewrite the whole .designer.cs file and your controls should now be in the "correct" order.
There are rare cases where this does not help. These include DataGridViewRows in embedded DataGridViews and embedded UserControls. In these cases I additionally do similar finishing work which includes adding and removing a button:
Save all files of the form or UC
open the designer view
add a button anywhere in the form or UC
optional: look at the .designer.cs file and/or save the form or UC
remove this button again
save the form or UC
The only way I know of to truely avoid this problem when using a merge style source control system such as subversion is to hand code the forms and not use the designer. Obviously, this would not be good because hand coding these forms can take a while.
The reason this happens is because the control properties are serialized by the designer in the order they are dropped on the form. Cutting and pasting can effect this order as well as moving a control so that it has a new parent (such as moving a control on to a panel when it was previously directly on the form).
I had this problem on a large project and had to imploy a rather ugly approach - diff the designer.cs files against the check-in target revision and manually merge them using a merge tool. This isn't ideal, but it is the only way I see this working consistently with svn or another merge style source control tool.
The other option would be to use a lock approach with source control, as others have pointed out, but this comes with unpleasant side effects as well.

How to create a tree-view preferences dialog type of interface in C#?

I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be.
What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense:
Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a lot of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?
A tidier way is to create separate forms for each 'pane' and, in each form constructor, set
this.TopLevel = false;
this.FormBorderStyle = FormBorderStyle.None;
this.Dock = DockStyle.Fill;
That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control.
Perhaps the main form could use a SplitContainer with a static TreeView in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using Hide/Show or BringToFront/SendToBack methods.
SeparateForm f = new SeparateForm();
MainFormSplitContainer.Panel2.Controls.Add(f);
f.Show();
Greg Hurlman wrote:
Why not just show/hide the proper container when a node is selected in the grid? Have the containers all sized appropriately in the same spot, and hide all but the default, which would be preselected in the grid on load.
Unfortunately, that's what I'm trying to avoid. I'm looking for an easy way to handle the interface during design time, with minimal reformatting code needed to get it working during run time.
I like Duncan's answer because it means the design of each node's interface can be kept completely separate. This means I don't get overlap on the snapping guidelines and other design time advantages.
I would probably create several panel classes based on a base class inheriting CustomControl. These controls would then have methods like Save/Load and stuff like that. If so I can design each of these panels separately.
I have used a Wizard control that in design mode, handled several pages, so that one could click next in the designer and design all the pages at once through the designer. Though this had several disadvantages when connecting code to the controls, it probably means that you could have a similar setup by building some designer classes. I have never myself written any designer classes in VS, so I can't say how to or if its worth it :-)
I'm a little curious of how you intend to handle the load/save of values to/from the controls? There must be a lot of code in one class if all your pages are in one big Form?
And yet another way would of course be to generate the gui code as each page is requested, using info about what type of settings there are.

Categories