Why does the Visual Studio Designer delete code? - c#

Several times throughout the course of our current project, the visual studio designer has made modifications that resulted in losing code. For example, event handlers wirings that were set up manually in the designer code were lost. Does anyone know why this happens?
Edit: I understand that editing these files manually is not a good idea, but it has also happened with other event wirings set up through the designer.

Well for starters read the XML at the top of your designer.cs file.
/// <summary>
/// Required method for Designer support - do not modify
/// contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
Generally you shouldn't be modifying these files as they are auto-generated. It's probably the reason why there is a slight attempt to hide the code within a branch, underneath the main partial class.
I have on occasion found that the process has removed its own auto-generated code that I've had to merge back in. Most commonly it decides it's not going to instantiate custom user controls anymore, so when I start running I get a NullReferenceException.
Really the answer is to put the code somewhere else, like in the constructor before calling the InitializeComponent() method. If fellow developers aren't aware of this, then you should inform them and educate them, the fact that the files are .designer.cs should raise questions even to newer developers as to why the strange extension.

You guys aren't modifying generated code files, are you? Like MyForm.Designer.cs? This is why we were given partial classes.

Because it is designer generated and more or less maintained code. It is recommended that you not add or modify code in the designer partial class manually exactly because of the behavior you described (I think it even mentions this in the generated file itself). If you need to wire up event handlers manually then do it in your custom code possibly the constructor of your control.

Write all necessary initialization code only in your own .cs file, you have number of places to do this, like form constructor and form Load event handler.

Moving the designer code into user maintained code classes defeats the benefits of being able to modify the user interface. Perhaps this might be something you would want to do if the program never needs to be modified again, but if that is the case... where is the benefit as well?
This issue of the designer class losing lines of code has existed since Visual Studio was initially released and has caused me countless nightmares because the loss occurred perhaps weeks before, when the program was previously modified.
I can't prove it but it seems obvious that something in Microsoft's code generator is failing and there isn't any alerts to tell you it crashed. So, Microsoft... fix what is crashing or at least, tell us about it when it happens.

Related

Create method with refactor shortcut, is there a way to chose between partial or non partial target?

So basically, I have a tool that I designed, that generates some code based on the model, and pastes this code automatically inside the .partial classes, on this approach, .partial is used for generated code, and his normal class is used for my manual code, this way I don´t loss my code everytime is auto-generated.
The problem is, in previous versions of visual studio, when you pressed CTRL+(dot) to refactor and create new methods, it automatically created this inside the regular file, not the partial. Knowing this I designed my tool to write auto-generated code on the partial.
Now i´m using Visual studio 15 and above, and it seems this changed, refactors are created into .partial files, making my approach annoying... I need constantly to move generated method.
is there a way to configure where to place this refactored methods?

Editing the InitializeComponent() method C#

I've gone through multiple resources on trying to find the use cases of when to manually add code to InitializeComponent, but haven't found anything concrete. This suggests we shouldn't do it - The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified
In the past, I had always used the form designer and never needed to manually make changes to InitializeComponent(). However at my new firm, the tech lead has completely ignored the form designer and manually added most UI elements within InitializeComponent (i.e. it has either been heavily edited, or completely re-written to the extent that the Designer can't recreate the GUI in VS, but the GUI is visible and fully functional at when the code is executed)
What is the advantage of not using the form designer? Is it just a matter of preference? Is manually editing/rewriting InitializeComponent for simple UI elements a good practice?
Thanks!
There are only a few reasons why one might need to edit InitializeComponent, such as:
To correct bugs introduced by a bad toolbox item designer.
To remove all traces of a control that cannot be deleted from the VS designer. (This has to be done carefully.)
To make quick "designer friendly" tweaks: changing a property value, adding a property setting, or removing a property setting. When adding a setting, I make sure it looks just like the designer-generated code.
After editing InitializeComponent, I always save & switch back to Designer mode to make sure I didn't break anything.
Any manual initialization code should be added outside InitializeComponent, e.g. OnLoaded() in a WinForms form or user control. As for fixing existing forms, it may be simple or nearly impossible depending on how complicated the form is, especially if controls have been added manually and required initialization methods (such as SuspendLayout, BeginInit) aren't being called.

Regarding Visual Studio Forms Method Calling From Program.cs and general logic advice

I'm trying to implement Blackjack via Visual Studio, but have just been introduced to it. Suppose I have a PictureBox representing a card in a hand. This box starts with an image of a face-down card, representing a card slot that hasn't been dealt to yet. I have a function in my Form object that changes the PictureBox image to another card image resource based on an integer parameter. This is all pretty standard.
What I'm having trouble with is actually calling the method from main. I could create a new Form object and set the auto-generated one to invisible, but I'd rather work with the form that's auto-generated. Should I just put all the game logic in the Form1.cs file? Does the auto-generated form object have some default name I can use?
I realize this seems pretty novice level, but it seems like Microsoft's support documentation would prefer you create entire projects from the designer view and doesn't help much for actually coding.
The typical model for a simple Forms program is to allow the Main() method in Program.cs to remain in its default form: set some things up, create an instance of your primary Form subclass (the class name by default will be Form1), and pass that to the Application.Run() method.
It is good design to have a "controller" object outside of the UI object. But especially if you are starting out, you may well find it simpler and easier to understand if that "controller" logic is also in your primary Form subclass.
In that case, yes…all of the code winds up in the one .cs file, and indeed in the one object.
Even with the controller logic in the Form object, you will still find it useful to keep the code that is essentially controller logic separate from that which is user-interface logic, and to use the C# #region directive to label these sections of code. That will help you keep a mental model that still separates the two roles within the same class.
Beyond this, there are lots of differing opinions, from the complete "shoot-from-the-hip" approach, to the extremely strict and rigorous adherence to specific design patterns. But the above is consistent with the pattern that the Visual Designer leads you to, and so is a fine place for beginners to start.

Constructor keeps disappearing

I have a c# program that interacts with an sql database. I added the database using Server Explorer, and now have a dbml file to interact with it. The name is MasterDatabase.dbml. The IDE generated several overloaded constructors in MasterDatabase.designer.cs.
I added another overloaded constructor that takes no parameters (every one the computer generated takes at least one parameter). The code works perfectly with this overloaded constructor, but it will occasionally disappear! The constructor will be there for days, and then one day I will run my code and get a bunch of errors saying that there is no constructor that takes 0 arguments. I will then go back to MasterDatabase.designer.cs, and my constructor is no longer there. So I add it again, and the cycle repeats itself.
Has anyone experienced this before? And more importantly, how do I fix it so that my constructor stops disappearing?
I did not post any code, because this is a general question, and I don't think my specific code will help solve the problem, but let me know if you need to see any of it and I will.
You generally don't want to modify those generated classes directly. Those classes may be rebuilt without warning. I don't have much experience in this, but I believe those generated classes are partial classes. Create a new .cs file completely, with the same class name (including the partial keyword) and add the constructor there.
The problem is you are editing a generated file. WPF uses partial classes to seperate YOUR code from GENERATED code. You can create 'partial' classes of your own, although this serves no particular use other than organization of code. To get to the point, whatever code you write in a partial class can be rewritten in any other partial class file, so long as the classes are same. So take your overloaded constructor and put it into a NON-GENERATED file. This will prevent the generator from editing any changes you have made in that file. If the code worked sometimes in the generated partial file, it should always work if put into a non-generated partial file, because the code is not altered by Visual.

Any way to fix components variable in Winforms Designer auto-generated code?

I'm experiencing a very nasty with Winforms Designer auto generated code. Sometimes it creates the components variable, and sometimes it doesn't. Even if there ARE components on the form that are designed to be used with an IContainer instance, such as ErrorProvider.
It seems to happens randomly. In this MSDN thread it is suggested to deactivate "Optimized Code Generation" in the designer's options. Unfortunately in my case it doesn't seem to have any effect.
Is anyone else experiencing this? What can be done to ensure that this variable always gets generated when needed?

Categories